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 <reporter.h>
37#include <richio.h>
38
39
41 m_exporter( aExporter )
42{
43 if( m_exporter.m_connectivityDepth == 0 )
44 m_exporter.rebuildConnectivity();
45
46 ++m_exporter.m_connectivityDepth;
47}
48
53
54bool NETLIST_EXPORTER_BASE::WriteNetlist( const wxString& aOutFileName, unsigned aNetlistOptions,
55 REPORTER& aReporter )
56{
57 try
58 {
59 CONNECTIVITY_SCOPE connectivity( *this );
60 return writeNetlist( aOutFileName, aNetlistOptions, aReporter );
61 }
62 catch( const IO_ERROR& error )
63 {
64 aReporter.Report( error.What(), RPT_SEVERITY_ERROR );
65 return false;
66 }
67 catch( const std::exception& error )
68 {
69 aReporter.Report( wxString::Format( _( "Failed to export schematic: %s" ), error.what() ),
71 return false;
72 }
73}
74
76{
77 m_exportNets.clear();
78 m_exportItemNets.clear();
79 m_schematic->RebuildConnectivity();
80 m_exportSheets = m_schematic->Hierarchy();
81
82 for( const SCH_SHEET_PATH& path : m_exportSheets )
83 {
84 auto& itemNets = m_exportItemNets[path];
85 auto collect = [&]( SCH_ITEM* item )
86 {
87 if( SCH_CONNECTION* connection = item->Connection( &path ) )
88 itemNets.emplace( item->m_Uuid, connection->Name() );
89 };
90
91 for( SCH_ITEM* item : path.LastScreen()->Items() )
92 {
93 collect( item );
94 item->RunOnChildren( collect, RECURSE_MODE::NO_RECURSE );
95 }
96 }
97
98 for( const auto& [key, subgraphs] : m_schematic->ConnectionGraph()->GetNetMap() )
99 {
100 EXPORT_NET result{ key.Name, false, {} };
101
102 for( CONNECTION_SUBGRAPH* subgraph : subgraphs )
103 {
104 result.hasNoConnect |= subgraph->GetNoConnect()
105 && subgraph->GetNoConnect()->Type() == SCH_NO_CONNECT_T;
106 const SCH_SHEET_PATH& path = subgraph->GetSheet();
107
108 for( SCH_ITEM* item : subgraph->GetItems() )
109 {
110 if( item->Type() == SCH_PIN_T )
111 result.pins.emplace_back( static_cast<SCH_PIN*>( item ), path );
112 }
113 }
114
115 m_exportNets.push_back( std::move( result ) );
116 }
117}
118
119std::optional<wxString> NETLIST_EXPORTER_BASE::itemNetName( const SCH_ITEM& aItem,
120 const SCH_SHEET_PATH& aPath ) const
121{
122 const auto sheet = m_exportItemNets.find( aPath );
123
124 if( sheet == m_exportItemNets.end() )
125 return std::nullopt;
126
127 const auto found = sheet->second.find( aItem.m_Uuid );
128 return found == sheet->second.end() ? std::nullopt : std::optional( found->second );
129}
130
131
132// a "less than" test on two LIB_SYMBOLs (.m_name wxStrings)
134 LIB_SYMBOL* const& libsymbol2 ) const
135{
136 // Use case specific GetName() wxString compare
137 return libsymbol1->GetLibId() < libsymbol2->GetLibId();
138}
139
140
141wxString NETLIST_EXPORTER_BASE::MakeCommandLine( const wxString& aFormatString,
142 const wxString& aNetlistFile,
143 const wxString& aFinalFile,
144 const wxString& aProjectPath )
145{
146 // Expand format symbols in the command line:
147 // %B => base filename of selected output file, minus path and extension.
148 // %P => project directory name, without trailing '/' or '\'.
149 // %I => full filename of the input file (the intermediate net file).
150 // %O => complete filename and path (but without extension) of the user chosen output file.
151
152 wxString ret = aFormatString;
153 wxFileName in = aNetlistFile;
154 wxFileName out = aFinalFile;
155 wxString str_out = out.GetFullPath();
156
157 ret.Replace( "%P", aProjectPath, true );
158 ret.Replace( "%B", out.GetName(), true );
159 ret.Replace( "%I", in.GetFullPath(), true );
160
161#ifdef __WINDOWS__
162 // A ugly hack to run xsltproc that has a serious bug on Window since a long time:
163 // the filename given after -o option (output filename) cannot use '\' in filename
164 // so replace if by '/' if possible (I mean if the filename does not start by "\\"
165 // that is a filename on a Windows server)
166
167 if( !str_out.StartsWith( "\\\\" ) )
168 str_out.Replace( "\\", "/" );
169#endif
170
171 ret.Replace( "%O", str_out, true );
172
173 return ret;
174}
175
176
178 const SCH_SHEET_PATH& aSheetPath )
179{
180 wxCHECK( aItem, nullptr );
181
182 wxString ref;
183
184 if( aItem->Type() != SCH_SYMBOL_T )
185 return nullptr;
186
187 // found next symbol
188 SCH_SYMBOL* symbol = (SCH_SYMBOL*) aItem;
189
190 // Power symbols and other symbols which have the reference starting with "#" are not
191 // included in netlist (pseudo or virtual symbols)
192 ref = symbol->GetRef( &aSheetPath );
193
194 if( ref[0] == wxChar( '#' ) )
195 return nullptr;
196
197 SCH_SCREEN* screen = aSheetPath.LastScreen();
198
199 wxCHECK( screen, nullptr );
200
201 auto it = screen->GetLibSymbols().find( symbol->GetSchSymbolLibraryName() );
202
203 if( it == screen->GetLibSymbols().end() )
204 return nullptr;
205
206 LIB_SYMBOL* libSymbol = it->second;
207
208 // If symbol is a "multi parts per package" type
209 if( libSymbol->GetUnitCount() > 1 )
210 {
211 // test if this reference has already been processed, and if so skip
212 if( m_referencesAlreadyFound.Lookup( ref ) )
213 return nullptr;
214 }
215
216 // record the usage of this library symbol entry.
217 m_libParts.insert( libSymbol ); // rejects non-unique pointers
218
219 return symbol;
220}
221
222
223std::vector<PIN_INFO> NETLIST_EXPORTER_BASE::CreatePinList( SCH_SYMBOL* aSymbol,
224 const SCH_SHEET_PATH& aSheetPath )
225{
226 std::vector<PIN_INFO> pins;
227
228 if( !aSymbol )
229 return pins;
230
231 wxString ref( aSymbol->GetRef( &aSheetPath ) );
232
233 // Power symbols and other symbols which have the reference starting with "#" are not
234 // included in netlist (pseudo or virtual symbols)
235 if( ( ref[0] == wxChar( '#' ) ) || aSymbol->IsPower() )
236 return pins;
237
238 // if( aSymbol->m_FlagControlMulti == 1 )
239 // continue; /* yes */
240 // removed because with multiple instances of one schematic (several sheets pointing to
241 // 1 screen), this will be erroneously be toggled.
242
243 if( !aSymbol->GetLibSymbolRef() )
244 return pins;
245
246 // If symbol is a "multi parts per package" type
247 if( aSymbol->GetLibSymbolRef()->GetUnitCount() > 1 )
248 {
249 // Collect all pins for this reference designator by searching the entire design for
250 // other parts with the same reference designator.
251 findAllUnitsOfSymbol( aSymbol, aSheetPath, pins );
252 }
253
254 else // GetUnitCount() <= 1 means one part per package
255 {
256 for( const SCH_PIN* pin : aSymbol->GetPins( &aSheetPath ) )
257 {
258 if( const auto netName = itemNetName( *pin, aSheetPath ) )
259 appendResolvedPins( pins, pin, aSheetPath, *netName );
260 }
261 }
262
263 // Sort pins in m_SortedSymbolPinList by pin number
264 std::sort( pins.begin(), pins.end(),
265 []( const PIN_INFO& lhs, const PIN_INFO& rhs )
266 {
267 return StrNumCmp( lhs.num, rhs.num, true ) < 0;
268 } );
269
270 // Remove duplicate Pins in m_SortedSymbolPinList
271 eraseDuplicatePins( pins );
272
273 // record the usage of this library symbol
274 m_libParts.insert( aSymbol->GetLibSymbolRef().get() ); // rejects non-unique pointers
275
276 return pins;
277}
278
279
280std::vector<wxString> NETLIST_EXPORTER_BASE::resolvePadNumbers( const SCH_PIN* aPin,
281 const SCH_SHEET_PATH& aSheetPath ) const
282{
283 // Shared resolution kernel for all netlist paths (issue #2282) so they cannot drift.
284 const wxString variantName = m_schematic ? m_schematic->GetCurrentVariant() : wxString();
285
286 if( m_kiway )
287 {
288 if( const SCH_SYMBOL* symbol = dynamic_cast<const SCH_SYMBOL*>( aPin->GetParentSymbol() ) )
289 {
290 wxString fpText = symbol->GetFootprintFieldText( &aSheetPath, RESOLVED, variantName );
291 LIB_ID fpId;
292
293 if( !fpText.IsEmpty() && fpId.Parse( fpText, true ) < 0 )
294 {
295 const std::set<wxString>& pads = footprintPads( fpId.GetUniStringLibId() );
296
297 if( !pads.empty() )
298 {
299 SCH_PIN::PAD_RESOLUTION state = SCH_PIN::PAD_RESOLUTION::MAPPED;
300 wxString pad = aPin->GetEffectivePadNumber( aSheetPath, variantName, fpId, &pads, &state );
301
302 if( state == SCH_PIN::PAD_RESOLUTION::UNMAPPED )
303 return {};
304
306 }
307 }
308 }
309 }
310
311 return ExpandStackedPinNotation( aPin->GetEffectivePadNumber( aSheetPath, variantName ) );
312}
313
314
315const std::set<wxString>& NETLIST_EXPORTER_BASE::footprintPads( const wxString& aFootprintId ) const
316{
317 auto it = m_footprintPadCache.find( aFootprintId );
318
319 if( it != m_footprintPadCache.end() )
320 return it->second;
321
322 std::set<wxString>& pads = m_footprintPadCache[aFootprintId];
323
324 if( m_kiway && !aFootprintId.IsEmpty() )
325 {
326 if( KIFACE* cvpcb = m_kiway->KiFACE( KIWAY::FACE_CVPCB ) )
327 {
328 typedef void ( *PAD_NUMBERS_FN_PTR )( const wxString&, PROJECT*, std::set<wxString>& );
329
330 if( auto fetch = (PAD_NUMBERS_FN_PTR) cvpcb->IfaceOrAddress( KIFACE_FOOTPRINT_PAD_NUMBERS ) )
331 fetch( aFootprintId, &m_schematic->Project(), pads );
332 }
333 }
334
335 return pads;
336}
337
338
339void NETLIST_EXPORTER_BASE::appendResolvedPins( std::vector<PIN_INFO>& aPins, const SCH_PIN* aPin,
340 const SCH_SHEET_PATH& aSheetPath, const wxString& aNetName )
341{
342 const wxString baseName = aPin->GetShownName();
343
344 for( const wxString& padNum : resolvePadNumbers( aPin, aSheetPath ) )
345 {
346 wxString pinName = baseName.IsEmpty() ? padNum : baseName + wxT( "_" ) + padNum;
347 aPins.emplace_back( padNum, aNetName, pinName, aPin->GetNumber() );
348 }
349}
350
351
352void NETLIST_EXPORTER_BASE::eraseDuplicatePins( std::vector<PIN_INFO>& aPins )
353{
354 for( unsigned ii = 0; ii < aPins.size(); ii++ )
355 {
356 if( aPins[ii].num.empty() )
357 continue;
358
359 // Search for duplicated pins and keep only one. Duplicate pin numbers can occur
360 // for multi-unit symbols with shared pins, or for symbols with the "duplicate pin
361 // numbers are jumpers" flag. In either case, all pins with the same number should
362 // connect to the same net. When they don't (user error), we prefer user-assigned
363 // nets over auto-generated ones to preserve user intent in the netlist.
364 // Because the pin list is sorted by pin number, duplicates are consecutive.
365 unsigned idxBest = ii;
366
367 for( unsigned jj = ii + 1; jj < aPins.size(); jj++ )
368 {
369 if( aPins[jj].num.empty() )
370 continue;
371
372 if( aPins[idxBest].num != aPins[jj].num )
373 break;
374
375 // A genuine many-to-one mapping collision - two *different* symbol pins resolved to
376 // the same pad on *different* nets - must survive so it stays visible and is flagged
377 // by ERC (issue #2282). Shared multi-unit pins and jumpers carry the same source pin
378 // number, so they still collapse below as before.
379 if( aPins[idxBest].netName != aPins[jj].netName && !aPins[idxBest].srcPin.IsEmpty()
380 && !aPins[jj].srcPin.IsEmpty() && aPins[idxBest].srcPin != aPins[jj].srcPin )
381 {
382 continue;
383 }
384
385 // Check if jj has a better (user-assigned) net than the current best.
386 // Prefer user-assigned nets over auto-generated "unconnected-(" or "Net-(" nets.
387 bool bestIsAuto = IsAutoGeneratedNetName( aPins[idxBest].netName );
388 bool jjIsAuto = IsAutoGeneratedNetName( aPins[jj].netName );
389
390 if( bestIsAuto && !jjIsAuto )
391 {
392 // jj has a user-assigned net while best has auto-generated; switch to jj
393 aPins[idxBest].num.clear();
394 idxBest = jj;
395 }
396 else
397 {
398 aPins[jj].num.clear();
399 }
400 }
401 }
402}
403
404
406 const SCH_SHEET_PATH& aSheetPath,
407 std::vector<PIN_INFO>& aPins )
408{
409 const wxString ref = aSchSymbol->GetRef( &aSheetPath );
410
411 for( const SCH_SHEET_PATH& sheet : m_exportSheets )
412 {
413 for( SCH_ITEM* item : sheet.LastScreen()->Items().OfType( SCH_SYMBOL_T ) )
414 {
415 auto* symbol = static_cast<SCH_SYMBOL*>( item );
416
417 if( symbol->GetRef( &sheet ).CmpNoCase( ref ) != 0 )
418 continue;
419
420 for( const SCH_PIN* pin : symbol->GetPins( &sheet ) )
421 {
422 if( const auto netName = itemNetName( *pin, sheet ) )
423 appendResolvedPins( aPins, pin, sheet, *netName );
424 }
425 }
426 }
427}
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:597
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:349
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:119
const LIB_ID & GetLibId() const override
Definition lib_symbol.h:188
int GetUnitCount() const override
CONNECTIVITY_SCOPE(NETLIST_EXPORTER_BASE &aExporter)
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).
NETLIST_EXPORTER_BASE(SCHEMATIC *aSchematic)
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:165
const SYMBOL * GetParentSymbol() const
Definition sch_item.cpp:287
PAD_RESOLUTION
Outcome of pin-to-pad resolution (issue #2282).
Definition sch_pin.h:173
const wxString & GetShownName() const
Definition sch_pin.cpp:680
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:731
const wxString & GetNumber() const
Definition sch_pin.h:142
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:503
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:75
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:183
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false) const override
bool IsPower() const override
@ RESOLVED
Definition common.h:93
#define _(s)
@ NO_RECURSE
Definition eda_item.h:52
@ KIFACE_FOOTPRINT_PAD_NUMBERS
Function pointer type: void (*)( const wxString& aFootprint, PROJECT* aProject, std::set<wxString>& a...
Definition kiface_ids.h:62
@ 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