KiCad PCB EDA Suite
Loading...
Searching...
No Matches
netlist_exporter_base.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 1992-2017 jp.charras at wanadoo.fr
5 * Copyright (C) 2013-2017 SoftPLC Corporation, Dick Hollenbeck <[email protected]>
6 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
23
24#include <string_utils.h>
25
26#include <trace_helpers.h>
27#include <connection_graph.h>
28#include <kiface_ids.h>
29#include <kiway.h>
30#include <lib_id.h>
31#include <sch_pin.h>
32#include <sch_reference_list.h>
33#include <sch_screen.h>
34#include <sch_symbol.h>
35#include <schematic.h>
36#include <advanced_config.h>
38#include <reporter.h>
39#include <richio.h>
40
41
43 m_exporter( aExporter )
44{
45 if( m_exporter.m_connectivityDepth == 0 )
46 m_exporter.rebuildConnectivity();
47
48 ++m_exporter.m_connectivityDepth;
49}
50
55
56bool NETLIST_EXPORTER_BASE::WriteNetlist( const wxString& aOutFileName, unsigned aNetlistOptions,
57 REPORTER& aReporter )
58{
59 try
60 {
61 CONNECTIVITY_SCOPE connectivity( *this );
62 return writeNetlist( aOutFileName, aNetlistOptions, aReporter );
63 }
64 catch( const IO_ERROR& error )
65 {
66 aReporter.Report( error.What(), RPT_SEVERITY_ERROR );
67 return false;
68 }
69 catch( const std::exception& error )
70 {
71 aReporter.Report( wxString::Format( _( "Failed to export schematic: %s" ), error.what() ),
73 return false;
74 }
75}
76
78{
79 m_exportNets.clear();
80 m_exportItemNets.clear();
81 m_schematic->RebuildConnectivity();
82 m_exportSheets = m_schematic->Hierarchy();
83
84 if( ADVANCED_CFG::GetCfg().m_ConnectivityEngine )
85 {
86 auto& facade = m_schematic->Connectivity();
87 std::map<KIID_PATH, const SCH_SHEET_PATH*> paths;
88
89 for( const SCH_SHEET_PATH& path : m_exportSheets )
90 paths.emplace( path.Path(), &path );
91
92 for( const auto& [key, row] : facade.Published().Rows() )
93 {
94 const auto& path = facade.Keys().Instance( key.inst );
95 const auto view = facade.Connection( key.item, path );
96
97 if( !view )
98 THROW_IO_ERROR( _( "Connectivity changed while preparing the netlist." ) );
99
100 const auto sheet = paths.find( path );
101
102 if( sheet == paths.end() )
103 THROW_IO_ERROR( _( "Connectivity contains an unknown sheet instance." ) );
104
105 m_exportItemNets[*sheet->second].emplace( key.item, view->Name() );
106 }
107
108 for( const auto& group : facade.GetNetMap() )
109 {
110 EXPORT_NET result{ group.name, false, {} };
111
112 for( const auto& net : group.instances )
113 {
114 if( !net.IsNet() )
115 continue;
116
117 const auto path = paths.find( net.Instance() );
118
119 if( path == paths.end() )
120 THROW_IO_ERROR( _( "Connectivity contains an unknown sheet instance." ) );
121
122 for( SCH_ITEM* item : net.Items() )
123 {
124 result.hasNoConnect |= item->Type() == SCH_NO_CONNECT_T;
125
126 if( item->Type() == SCH_PIN_T )
127 result.pins.emplace_back( static_cast<SCH_PIN*>( item ), *path->second );
128 }
129 }
130
131 m_exportNets.push_back( std::move( result ) );
132 }
133
134 return;
135 }
136
137 for( const SCH_SHEET_PATH& path : m_exportSheets )
138 {
139 auto& itemNets = m_exportItemNets[path];
140 auto collect = [&]( SCH_ITEM* item )
141 {
142 if( SCH_CONNECTION* connection = item->Connection( &path ) )
143 itemNets.emplace( item->m_Uuid, connection->Name() );
144 };
145
146 for( SCH_ITEM* item : path.LastScreen()->Items() )
147 {
148 collect( item );
149 item->RunOnChildren( collect, RECURSE_MODE::NO_RECURSE );
150 }
151 }
152
153 for( const auto& [key, subgraphs] : m_schematic->ConnectionGraph()->GetNetMap() )
154 {
155 EXPORT_NET result{ key.Name, false, {} };
156
157 for( CONNECTION_SUBGRAPH* subgraph : subgraphs )
158 {
159 result.hasNoConnect |= subgraph->GetNoConnect()
160 && subgraph->GetNoConnect()->Type() == SCH_NO_CONNECT_T;
161 const SCH_SHEET_PATH& path = subgraph->GetSheet();
162
163 for( SCH_ITEM* item : subgraph->GetItems() )
164 {
165 if( item->Type() == SCH_PIN_T )
166 result.pins.emplace_back( static_cast<SCH_PIN*>( item ), path );
167 }
168 }
169
170 m_exportNets.push_back( std::move( result ) );
171 }
172}
173
174std::optional<wxString> NETLIST_EXPORTER_BASE::itemNetName( const SCH_ITEM& aItem,
175 const SCH_SHEET_PATH& aPath ) const
176{
177 const auto sheet = m_exportItemNets.find( aPath );
178
179 if( sheet == m_exportItemNets.end() )
180 return std::nullopt;
181
182 const auto found = sheet->second.find( aItem.m_Uuid );
183 return found == sheet->second.end() ? std::nullopt : std::optional( found->second );
184}
185
186
187// a "less than" test on two LIB_SYMBOLs (.m_name wxStrings)
189 LIB_SYMBOL* const& libsymbol2 ) const
190{
191 // Use case specific GetName() wxString compare
192 return libsymbol1->GetLibId() < libsymbol2->GetLibId();
193}
194
195
196wxString NETLIST_EXPORTER_BASE::MakeCommandLine( const wxString& aFormatString,
197 const wxString& aNetlistFile,
198 const wxString& aFinalFile,
199 const wxString& aProjectPath )
200{
201 // Expand format symbols in the command line:
202 // %B => base filename of selected output file, minus path and extension.
203 // %P => project directory name, without trailing '/' or '\'.
204 // %I => full filename of the input file (the intermediate net file).
205 // %O => complete filename and path (but without extension) of the user chosen output file.
206
207 wxString ret = aFormatString;
208 wxFileName in = aNetlistFile;
209 wxFileName out = aFinalFile;
210 wxString str_out = out.GetFullPath();
211
212 ret.Replace( "%P", aProjectPath, true );
213 ret.Replace( "%B", out.GetName(), true );
214 ret.Replace( "%I", in.GetFullPath(), true );
215
216#ifdef __WINDOWS__
217 // A ugly hack to run xsltproc that has a serious bug on Window since a long time:
218 // the filename given after -o option (output filename) cannot use '\' in filename
219 // so replace if by '/' if possible (I mean if the filename does not start by "\\"
220 // that is a filename on a Windows server)
221
222 if( !str_out.StartsWith( "\\\\" ) )
223 str_out.Replace( "\\", "/" );
224#endif
225
226 ret.Replace( "%O", str_out, true );
227
228 return ret;
229}
230
231
233 const SCH_SHEET_PATH& aSheetPath )
234{
235 wxCHECK( aItem, nullptr );
236
237 wxString ref;
238
239 if( aItem->Type() != SCH_SYMBOL_T )
240 return nullptr;
241
242 // found next symbol
243 SCH_SYMBOL* symbol = (SCH_SYMBOL*) aItem;
244
245 // Power symbols and other symbols which have the reference starting with "#" are not
246 // included in netlist (pseudo or virtual symbols)
247 ref = symbol->GetRef( &aSheetPath );
248
249 if( ref[0] == wxChar( '#' ) )
250 return nullptr;
251
252 SCH_SCREEN* screen = aSheetPath.LastScreen();
253
254 wxCHECK( screen, nullptr );
255
256 auto it = screen->GetLibSymbols().find( symbol->GetSchSymbolLibraryName() );
257
258 if( it == screen->GetLibSymbols().end() )
259 return nullptr;
260
261 LIB_SYMBOL* libSymbol = it->second;
262
263 // If symbol is a "multi parts per package" type
264 if( libSymbol->GetUnitCount() > 1 )
265 {
266 // test if this reference has already been processed, and if so skip
267 if( m_referencesAlreadyFound.Lookup( ref ) )
268 return nullptr;
269 }
270
271 // record the usage of this library symbol entry.
272 m_libParts.insert( libSymbol ); // rejects non-unique pointers
273
274 return symbol;
275}
276
277
278std::vector<PIN_INFO> NETLIST_EXPORTER_BASE::CreatePinList( SCH_SYMBOL* aSymbol,
279 const SCH_SHEET_PATH& aSheetPath )
280{
281 std::vector<PIN_INFO> pins;
282
283 if( !aSymbol )
284 return pins;
285
286 wxString ref( aSymbol->GetRef( &aSheetPath ) );
287
288 // Power symbols and other symbols which have the reference starting with "#" are not
289 // included in netlist (pseudo or virtual symbols)
290 if( ( ref[0] == wxChar( '#' ) ) || aSymbol->IsPower() )
291 return pins;
292
293 // if( aSymbol->m_FlagControlMulti == 1 )
294 // continue; /* yes */
295 // removed because with multiple instances of one schematic (several sheets pointing to
296 // 1 screen), this will be erroneously be toggled.
297
298 if( !aSymbol->GetLibSymbolRef() )
299 return pins;
300
301 // If symbol is a "multi parts per package" type
302 if( aSymbol->GetLibSymbolRef()->GetUnitCount() > 1 )
303 {
304 // Collect all pins for this reference designator by searching the entire design for
305 // other parts with the same reference designator.
306 findAllUnitsOfSymbol( aSymbol, aSheetPath, pins );
307 }
308
309 else // GetUnitCount() <= 1 means one part per package
310 {
311 for( const SCH_PIN* pin : aSymbol->GetPins( &aSheetPath ) )
312 {
313 if( const auto netName = itemNetName( *pin, aSheetPath ) )
314 appendResolvedPins( pins, pin, aSheetPath, *netName );
315 }
316 }
317
318 // Sort pins in m_SortedSymbolPinList by pin number
319 std::sort( pins.begin(), pins.end(),
320 []( const PIN_INFO& lhs, const PIN_INFO& rhs )
321 {
322 return StrNumCmp( lhs.num, rhs.num, true ) < 0;
323 } );
324
325 // Remove duplicate Pins in m_SortedSymbolPinList
326 eraseDuplicatePins( pins );
327
328 // record the usage of this library symbol
329 m_libParts.insert( aSymbol->GetLibSymbolRef().get() ); // rejects non-unique pointers
330
331 return pins;
332}
333
334
335std::vector<wxString> NETLIST_EXPORTER_BASE::resolvePadNumbers( const SCH_PIN* aPin,
336 const SCH_SHEET_PATH& aSheetPath ) const
337{
338 // Shared resolution kernel for all netlist paths (issue #2282) so they cannot drift.
339 const wxString variantName = m_schematic ? m_schematic->GetCurrentVariant() : wxString();
340
341 if( m_kiway )
342 {
343 if( const SCH_SYMBOL* symbol = dynamic_cast<const SCH_SYMBOL*>( aPin->GetParentSymbol() ) )
344 {
345 wxString fpText = symbol->GetFootprintFieldText( &aSheetPath, RESOLVED, variantName );
346 LIB_ID fpId;
347
348 if( !fpText.IsEmpty() && fpId.Parse( fpText, true ) < 0 )
349 {
350 const std::set<wxString>& pads = footprintPads( fpId.GetUniStringLibId() );
351
352 if( !pads.empty() )
353 {
354 SCH_PIN::PAD_RESOLUTION state = SCH_PIN::PAD_RESOLUTION::MAPPED;
355 wxString pad = aPin->GetEffectivePadNumber( aSheetPath, variantName, fpId, &pads, &state );
356
357 if( state == SCH_PIN::PAD_RESOLUTION::UNMAPPED )
358 return {};
359
361 }
362 }
363 }
364 }
365
366 return ExpandStackedPinNotation( aPin->GetEffectivePadNumber( aSheetPath, variantName ) );
367}
368
369
370const std::set<wxString>& NETLIST_EXPORTER_BASE::footprintPads( const wxString& aFootprintId ) const
371{
372 auto it = m_footprintPadCache.find( aFootprintId );
373
374 if( it != m_footprintPadCache.end() )
375 return it->second;
376
377 std::set<wxString>& pads = m_footprintPadCache[aFootprintId];
378
379 if( m_kiway && !aFootprintId.IsEmpty() )
380 {
381 if( KIFACE* cvpcb = m_kiway->KiFACE( KIWAY::FACE_CVPCB ) )
382 {
383 typedef void ( *PAD_NUMBERS_FN_PTR )( const wxString&, PROJECT*, std::set<wxString>& );
384
385 if( auto fetch = (PAD_NUMBERS_FN_PTR) cvpcb->IfaceOrAddress( KIFACE_FOOTPRINT_PAD_NUMBERS ) )
386 fetch( aFootprintId, &m_schematic->Project(), pads );
387 }
388 }
389
390 return pads;
391}
392
393
394void NETLIST_EXPORTER_BASE::appendResolvedPins( std::vector<PIN_INFO>& aPins, const SCH_PIN* aPin,
395 const SCH_SHEET_PATH& aSheetPath, const wxString& aNetName )
396{
397 const wxString baseName = aPin->GetShownName();
398
399 for( const wxString& padNum : resolvePadNumbers( aPin, aSheetPath ) )
400 {
401 wxString pinName = baseName.IsEmpty() ? padNum : baseName + wxT( "_" ) + padNum;
402 aPins.emplace_back( padNum, aNetName, pinName, aPin->GetNumber() );
403 }
404}
405
406
407void NETLIST_EXPORTER_BASE::eraseDuplicatePins( std::vector<PIN_INFO>& aPins )
408{
409 for( unsigned ii = 0; ii < aPins.size(); ii++ )
410 {
411 if( aPins[ii].num.empty() )
412 continue;
413
414 // Search for duplicated pins and keep only one. Duplicate pin numbers can occur
415 // for multi-unit symbols with shared pins, or for symbols with the "duplicate pin
416 // numbers are jumpers" flag. In either case, all pins with the same number should
417 // connect to the same net. When they don't (user error), we prefer user-assigned
418 // nets over auto-generated ones to preserve user intent in the netlist.
419 // Because the pin list is sorted by pin number, duplicates are consecutive.
420 unsigned idxBest = ii;
421
422 for( unsigned jj = ii + 1; jj < aPins.size(); jj++ )
423 {
424 if( aPins[jj].num.empty() )
425 continue;
426
427 if( aPins[idxBest].num != aPins[jj].num )
428 break;
429
430 // A genuine many-to-one mapping collision - two *different* symbol pins resolved to
431 // the same pad on *different* nets - must survive so it stays visible and is flagged
432 // by ERC (issue #2282). Shared multi-unit pins and jumpers carry the same source pin
433 // number, so they still collapse below as before.
434 if( aPins[idxBest].netName != aPins[jj].netName && !aPins[idxBest].srcPin.IsEmpty()
435 && !aPins[jj].srcPin.IsEmpty() && aPins[idxBest].srcPin != aPins[jj].srcPin )
436 {
437 continue;
438 }
439
440 // Check if jj has a better (user-assigned) net than the current best.
441 // Prefer user-assigned nets over auto-generated "unconnected-(" or "Net-(" nets.
442 bool bestIsAuto = IsAutoGeneratedNetName( aPins[idxBest].netName );
443 bool jjIsAuto = IsAutoGeneratedNetName( aPins[jj].netName );
444
445 if( bestIsAuto && !jjIsAuto )
446 {
447 // jj has a user-assigned net while best has auto-generated; switch to jj
448 aPins[idxBest].num.clear();
449 idxBest = jj;
450 }
451 else
452 {
453 aPins[jj].num.clear();
454 }
455 }
456 }
457}
458
459
461 const SCH_SHEET_PATH& aSheetPath,
462 std::vector<PIN_INFO>& aPins )
463{
464 const wxString ref = aSchSymbol->GetRef( &aSheetPath );
465
466 for( const SCH_SHEET_PATH& sheet : m_exportSheets )
467 {
468 for( SCH_ITEM* item : sheet.LastScreen()->Items().OfType( SCH_SYMBOL_T ) )
469 {
470 auto* symbol = static_cast<SCH_SYMBOL*>( item );
471
472 if( symbol->GetRef( &sheet ).CmpNoCase( ref ) != 0 )
473 continue;
474
475 for( const SCH_PIN* pin : symbol->GetPins( &sheet ) )
476 {
477 if( const auto netName = itemNetName( *pin, sheet ) )
478 appendResolvedPins( aPins, pin, sheet, *netName );
479 }
480 }
481 }
482}
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
A subgraph is a set of items that are electrically connected on a single sheet.
A base class for most all the KiCad significant classes used in schematics and boards.
Definition eda_item.h:98
const KIID m_Uuid
Definition eda_item.h:599
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
virtual const wxString What() const
A composite of Problem() and Where()
virtual const char * what() const override
std::exception interface, returned as UTF-8
@ FACE_CVPCB
Definition kiway.h:357
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
int Parse(const UTF8 &aId, bool aFix=false)
Parse LIB_ID with the information from aId.
Definition lib_id.cpp:65
wxString GetUniStringLibId() const
Definition lib_id.h:144
Define a library symbol object.
Definition lib_symbol.h:114
const LIB_ID & GetLibId() const override
Definition lib_symbol.h:190
int GetUnitCount() const override
CONNECTIVITY_SCOPE(NETLIST_EXPORTER_BASE &aExporter)
NETLIST_EXPORTER_BASE(SCHEMATIC *aSchematic, KIWAY *aKiway)
SCHEMATIC * m_schematic
The schematic we're generating a netlist for.
virtual bool writeNetlist(const wxString &aOutFileName, unsigned aNetlistOptions, REPORTER &aReporter)
std::optional< wxString > itemNetName(const SCH_ITEM &aItem, const SCH_SHEET_PATH &aPath) const
const std::set< wxString > & footprintPads(const wxString &aFootprintId) const
void findAllUnitsOfSymbol(SCH_SYMBOL *aSchSymbol, const SCH_SHEET_PATH &aSheetPath, std::vector< PIN_INFO > &aPins)
Find all units for symbols with multiple symbols per package.
SCH_SYMBOL * findNextSymbol(EDA_ITEM *aItem, const SCH_SHEET_PATH &aSheetPath)
Check if the given symbol should be processed for netlisting.
std::map< wxString, std::set< wxString > > m_footprintPadCache
std::set< LIB_SYMBOL *, LIB_SYMBOL_LESS_THAN > m_libParts
unique library symbols used. LIB_SYMBOL items are sorted by names
void eraseDuplicatePins(std::vector< PIN_INFO > &pins)
Erase duplicate pins.
std::vector< wxString > resolvePadNumbers(const SCH_PIN *aPin, const SCH_SHEET_PATH &aSheetPath) const
Resolve aPin to its effective pad number(s) for every netlist path (issue #2282).
std::map< SCH_SHEET_PATH, std::unordered_map< KIID, wxString > > m_exportItemNets
UNIQUE_STRINGS m_referencesAlreadyFound
Used for "multiple symbols per package" symbols to avoid processing a lib symbol more than once.
std::vector< EXPORT_NET > m_exportNets
bool WriteNetlist(const wxString &aOutFileName, unsigned aNetlistOptions, REPORTER &aReporter)
Write to specified output file.
static wxString MakeCommandLine(const wxString &aFormatString, const wxString &aNetlistFile, const wxString &aFinalFile, const wxString &aProjectDirectory)
Build up a string that describes a command line for executing a child process.
void appendResolvedPins(std::vector< PIN_INFO > &aPins, const SCH_PIN *aPin, const SCH_SHEET_PATH &aSheetPath, const wxString &aNetName)
Resolve aPin to its pad number(s) and append a PIN_INFO for each (issue #2282).
std::vector< PIN_INFO > CreatePinList(SCH_SYMBOL *aSymbol, const SCH_SHEET_PATH &aSheetPath)
Find a symbol from the DrawList and builds its pin list.
Container for project specific data.
Definition project.h:63
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:73
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)
Report a string with a given severity.
Definition reporter.h:102
Each graphical item can have a SCH_CONNECTION describing its logical connection (to a bus or net).
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition sch_item.h:170
const SYMBOL * GetParentSymbol() const
Definition sch_item.cpp:350
PAD_RESOLUTION
Outcome of pin-to-pad resolution (issue #2282).
Definition sch_pin.h:175
const wxString & GetShownName() const
Definition sch_pin.cpp:697
wxString GetEffectivePadNumber(const SCH_SHEET_PATH &aSheet, const wxString &aVariantName, const LIB_ID &aFootprintLibId, const std::set< wxString > *aFootprintPadNumbers, PAD_RESOLUTION *aState=nullptr) const
Resolve the footprint pad number this symbol pin lands on (issue #2282).
Definition sch_pin.cpp:748
const wxString & GetNumber() const
Definition sch_pin.h:144
const std::map< wxString, LIB_SYMBOL * > & GetLibSymbols() const
Fetch a list of unique LIB_SYMBOL object pointers required to properly render each SCH_SYMBOL in this...
Definition sch_screen.h:557
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
SCH_SCREEN * LastScreen()
Schematic symbol object.
Definition sch_symbol.h:73
wxString GetSchSymbolLibraryName() const
std::vector< const SCH_PIN * > GetPins(const SCH_SHEET_PATH *aSheet) const
Retrieve a list of the SCH_PINs for the given sheet path.
std::unique_ptr< LIB_SYMBOL > & GetLibSymbolRef()
Definition sch_symbol.h:182
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false) const override
bool IsPower() const override
@ RESOLVED
Definition common.h:95
#define _(s)
@ NO_RECURSE
Definition eda_item.h:52
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
@ KIFACE_FOOTPRINT_PAD_NUMBERS
Function pointer type: void (*)( const wxString& aFootprint, PROJECT* aProject, std::set<wxString>& a...
Definition kiface_ids.h:72
@ RPT_SEVERITY_ERROR
std::vector< wxString > ExpandStackedPinNotation(const wxString &aPinName, bool *aValid)
Expand stacked pin notation like [1,2,3], [1-4], [A1-A4], or [AA1-AA3,AB4,CD12-CD14] into individual ...
bool IsAutoGeneratedNetName(const wxString &aNetName)
Recognize the reserved prefixes used for generated pin-net names.
Implement a participant in the KIWAY alchemy.
Definition kiway.h:153
bool operator()(LIB_SYMBOL *const &libsymbol1, LIB_SYMBOL *const &libsymbol2) const
std::string path
KIBIS_PIN * pin
wxString result
Test unit parsing edge cases and error handling.
wxLogTrace helper definitions.
@ SCH_NO_CONNECT_T
Definition typeinfo.h:156
@ SCH_SYMBOL_T
Definition typeinfo.h:168
@ SCH_PIN_T
Definition typeinfo.h:149