KiCad PCB EDA Suite
Loading...
Searching...
No Matches
drc_re_rule_saver.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) 2024 KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20#include "drc_re_rule_saver.h"
21
22#include <board.h>
23#include <kiplatform/io.h>
24#include <lset.h>
25#include <tuple>
26#include <string_utils.h>
27
28#include <drc_rules_lexer.h>
29
32
33
34namespace
35{
36
37wxString formatLayerClause( const wxString& aLayerSource )
38{
39 if( aLayerSource.IsEmpty() )
40 return wxEmptyString;
41
42 if( aLayerSource == DRC_RULES_LEXER::TokenName( DRCRULE_T::T_outer )
43 || aLayerSource == DRC_RULES_LEXER::TokenName( DRCRULE_T::T_inner ) )
44 return wxString::Format( wxS( "(layer %s)" ), aLayerSource );
45
46 return wxString::Format( wxS( "(layer \"%s\")" ), EscapeString( aLayerSource, CTX_QUOTED_STR ) );
47}
48
49
50std::pair<wxString, wxString> splitLeadingTrivia( const wxString& aTrivia )
51{
52 size_t blank = aTrivia.rfind( wxS( "\n\n" ) );
53
54 if( blank == wxString::npos )
55 return { wxEmptyString, aTrivia };
56
57 return { aTrivia.Left( blank + 2 ), aTrivia.Mid( blank + 2 ) };
58}
59
60
61wxString savedCondition( const DRC_RE_LOADED_PANEL_ENTRY& aEntry )
62{
63 wxString predicate = aEntry.constraintData ? aEntry.constraintData->GetConditionPredicate() : wxString();
64
65 if( predicate.IsEmpty() )
66 return aEntry.condition;
67
68 if( aEntry.condition.IsEmpty() )
69 return predicate;
70
71 return predicate + wxS( " && " ) + aEntry.condition;
72}
73}
74
75
79
80
81bool DRC_RULE_SAVER::SaveFile( const wxString& aPath,
82 const std::vector<DRC_RE_LOADED_PANEL_ENTRY>& aEntries,
83 const BOARD* aBoard,
84 const DRC_RE_FILE_TRIVIA& aTrivia )
85{
86 wxString content = GenerateRulesText( aEntries, aBoard, aTrivia );
87 std::string utf8 = std::string( content.mb_str( wxConvUTF8 ) );
88
89 return KIPLATFORM::IO::AtomicWriteFile( aPath, utf8.data(), utf8.size() );
90}
91
92
93wxString DRC_RULE_SAVER::GenerateRulesText( const std::vector<DRC_RE_LOADED_PANEL_ENTRY>& aEntries,
94 const BOARD* aBoard,
95 const DRC_RE_FILE_TRIVIA& aTrivia )
96{
97 wxString result = aTrivia.header;
98
99 if( result.IsEmpty() )
100 result = wxS( "(version 2)" );
101
102 // Constraints with the same group came from one rule and go back into one. The layer
103 // source tells "outer" and "inner" of the same name apart.
104 // A predicate such as a via type narrows only its own part, so that part becomes its own rule
105 using GroupKey = std::tuple<int, wxString, wxString, wxString>;
106
107 std::vector<std::pair<GroupKey, std::vector<const DRC_RE_LOADED_PANEL_ENTRY*>>>
108 groupedEntries;
109 std::map<GroupKey, size_t> groupIndex;
110
111 for( const DRC_RE_LOADED_PANEL_ENTRY& entry : aEntries )
112 {
113 auto key = std::make_tuple( entry.ruleGroupId, entry.ruleName, savedCondition( entry ), entry.layerSource );
114 auto it = groupIndex.find( key );
115
116 if( it == groupIndex.end() )
117 {
118 groupIndex[key] = groupedEntries.size();
119 groupedEntries.push_back( { key, { &entry } } );
120 }
121 else
122 {
123 groupedEntries[it->second].second.push_back( &entry );
124 }
125 }
126
127 size_t triviaCount = aTrivia.leadingTrivia.size();
128 std::vector<wxString> floating( triviaCount );
129 std::vector<wxString> attached( triviaCount );
130 std::vector<bool> present( triviaCount, false );
131
132 for( size_t i = 0; i < triviaCount; ++i )
133 std::tie( floating[i], attached[i] ) = splitLeadingTrivia( aTrivia.leadingTrivia[i] );
134
135 // A group that generates nothing leaves its comment to the trivia, the way a deleted rule
136 // does, so every rule's text is known before any comment is placed.
137 std::vector<std::pair<int, wxString>> rules;
138
139 size_t nextTrivia = 0;
140
141 auto emitUpTo = [&]( size_t aLast )
142 {
143 while( nextTrivia <= aLast )
144 {
145 result += floating[nextTrivia];
146
147 if( !present[nextTrivia] )
148 result += attached[nextTrivia];
149
150 nextTrivia++;
151 }
152 };
153
154 for( const auto& [key, entries] : groupedEntries )
155 {
156 wxString ruleText;
157
158 // An untouched rule goes back exactly as it was read.
159 bool anyEdited = false;
160 wxString originalText;
161
162 for( const DRC_RE_LOADED_PANEL_ENTRY* entry : entries )
163 {
164 if( entry->wasEdited )
165 anyEdited = true;
166
167 if( originalText.IsEmpty() )
168 originalText = entry->originalRuleText;
169 }
170
171 if( !anyEdited && !originalText.IsEmpty()
172 && static_cast<int>( entries.size() ) == entries[0]->originalEntryCount )
173 {
174 ruleText = originalText;
175 }
176 else if( entries.size() == 1 )
177 {
178 // Single entry, no merge needed
179 ruleText = generateRuleText( *entries[0], aBoard );
180 }
181 else
182 {
183 // Multiple entries with same name/condition need merging
184 ruleText = generateMergedRuleText( entries, aBoard );
185 }
186
187 if( ruleText.IsEmpty() )
188 continue;
189
190 rules.emplace_back( entries[0]->sourceRule, ruleText );
191 }
192
193 for( const auto& [source, ruleText] : rules )
194 {
195 if( source >= 0 && static_cast<size_t>( source ) < triviaCount )
196 present[source] = true;
197 }
198
199 std::vector<bool> attachedWritten( triviaCount, false );
200
201 for( const auto& [source, ruleText] : rules )
202 {
203 bool known = source >= 0 && static_cast<size_t>( source ) < triviaCount;
204
205 if( known && static_cast<size_t>( source ) >= nextTrivia )
206 emitUpTo( source );
207 else
208 result += wxS( "\n" );
209
210 // Comments of deleted rules are kept, and a file rule split by an edit emits its own only once
211 if( known && !attachedWritten[source] )
212 {
213 if( !attached[source].StartsWith( wxS( "\n" ) ) && !result.EndsWith( wxS( "\n" ) ) )
214 result += wxS( "\n" );
215
216 result += attached[source];
217 attachedWritten[source] = true;
218 }
219
220 result += ruleText;
221 }
222
223 if( triviaCount > 0 )
224 emitUpTo( triviaCount - 1 );
225
226 if( aTrivia.header.IsEmpty() )
227 result += wxS( "\n" );
228 else
229 result += aTrivia.trailer;
230
231 return result;
232}
233
234
236 const BOARD* aBoard )
237{
238 if( !aEntry.constraintData )
239 return wxEmptyString;
240
241 wxString ruleText = aEntry.constraintData->GetGeneratedRule();
242
243 if( ruleText.IsEmpty() || aEntry.panelType == SILK_TO_SOLDERMASK_CLEARANCE
244 || aEntry.panelType == SILK_TO_SILK_CLEARANCE )
245 {
247 ctx.ruleName = aEntry.ruleName;
248 ctx.conditionExpression = aEntry.condition;
250 ctx.comment = aEntry.constraintData->GetComment();
251
253 {
254 wxString silkCond;
255
256 if( aEntry.layerCondition.test( F_SilkS ) && !aEntry.layerCondition.test( B_SilkS ) )
257 silkCond = wxS( "L == 'F.Mask'" );
258 else if( aEntry.layerCondition.test( B_SilkS ) && !aEntry.layerCondition.test( F_SilkS ) )
259 silkCond = wxS( "L == 'B.Mask'" );
260 else
261 silkCond = wxS( "L == 'F.Mask' || L == 'B.Mask'" );
262
263 if( !ctx.conditionExpression.IsEmpty() )
264 ctx.conditionExpression = wxS( "(" ) + silkCond + wxS( ") && " ) + ctx.conditionExpression;
265 else
266 ctx.conditionExpression = silkCond;
267 }
268 else if( aEntry.panelType == SILK_TO_SILK_CLEARANCE )
269 {
270 wxString silkCond;
271
272 if( aEntry.layerCondition.test( F_SilkS ) && !aEntry.layerCondition.test( B_SilkS ) )
273 silkCond = wxS( "L == 'F.SilkS'" );
274 else if( aEntry.layerCondition.test( B_SilkS ) && !aEntry.layerCondition.test( F_SilkS ) )
275 silkCond = wxS( "L == 'B.SilkS'" );
276 else
277 silkCond = wxS( "L == 'F.SilkS' || L == 'B.SilkS'" );
278
279 if( !ctx.conditionExpression.IsEmpty() )
280 ctx.conditionExpression = wxS( "(" ) + silkCond + wxS( ") && " ) + ctx.conditionExpression;
281 else
282 ctx.conditionExpression = silkCond;
283 }
284 else if( aBoard )
285 {
286 if( !aEntry.layerSource.IsEmpty() )
287 ctx.layerClause = formatLayerClause( aEntry.layerSource );
288 else
290 }
291
292 ruleText = aEntry.constraintData->GenerateRule( ctx );
293 }
294
295 // If severity is specified and not default, we need to inject it
296 // The GenerateRule method should handle this, but we verify here
298 {
299 wxString severityClause = generateSeverityClause( aEntry.severity );
300
301 if( !severityClause.IsEmpty() && !ruleText.Contains( "(severity" ) )
302 {
303 // Insert severity clause before the closing paren
304 size_t lastParen = ruleText.rfind( ')' );
305
306 if( lastParen != wxString::npos )
307 {
308 ruleText = ruleText.Left( lastParen ) + "\n\t" + severityClause + ")";
309 }
310 }
311 }
312
313 return ruleText;
314}
315
316
318{
319 // The parser gives a rule without a layer clause every layer
320 if( !aLayers.any() || aLayers == LSET::AllLayersMask() )
321 return wxEmptyString;
322
323 if( ( aLayers & LSET::AllCuMask() ) == LSET::ExternalCuMask() )
324 return wxString::Format( wxS( "(layer %s)" ), DRC_RULES_LEXER::TokenName( DRCRULE_T::T_outer ) );
325
326 if( ( aLayers & LSET::AllCuMask() ) == LSET::InternalCuMask() )
327 return wxString::Format( wxS( "(layer %s)" ), DRC_RULES_LEXER::TokenName( DRCRULE_T::T_inner ) );
328
329 // The parser only accepts a single layer name, and a user name only where the board registered
330 // it, so emit the canonical name of the first layer. Multi-layer sets use outer or inner above
331 for( PCB_LAYER_ID layer : aLayers.Seq() )
332 return wxString::Format( wxS( "(layer \"%s\")" ), LSET::Name( layer ) );
333
334 return wxEmptyString;
335}
336
337
339{
340 switch( aSeverity )
341 {
342 case RPT_SEVERITY_IGNORE: return "(severity ignore)";
343 case RPT_SEVERITY_WARNING: return "(severity warning)";
344 case RPT_SEVERITY_ERROR: return "(severity error)";
345 case RPT_SEVERITY_EXCLUSION: return "(severity exclusion)";
346 default: return wxEmptyString;
347 }
348}
349
350
352 const std::vector<const DRC_RE_LOADED_PANEL_ENTRY*>& aEntries,
353 const BOARD* aBoard )
354{
355 if( aEntries.empty() )
356 return wxEmptyString;
357
358 const DRC_RE_LOADED_PANEL_ENTRY* firstEntry = aEntries[0];
359
361 ctx.ruleName = firstEntry->ruleName;
362 ctx.conditionExpression = savedCondition( *firstEntry );
363
364 if( firstEntry->constraintData )
365 ctx.comment = firstEntry->constraintData->GetComment();
366
367 // Generate layer clause from first entry with layer info (all entries in a
368 // merged group share the same layerSource because it's part of the grouping key)
369 for( const auto* entry : aEntries )
370 {
371 if( entry->layerCondition.any() && aBoard )
372 {
373 if( !entry->layerSource.IsEmpty() )
374 ctx.layerClause = formatLayerClause( entry->layerSource );
375 else
376 ctx.layerClause = generateLayerClause( entry->layerCondition );
377
378 break;
379 }
380 }
381
382 // Collect all constraint clauses from all entries
383 std::vector<wxString> allClauses;
384
385 for( const auto* entry : aEntries )
386 {
387 if( entry->constraintData )
388 {
390 entryCtx.ruleName = entry->ruleName;
391 entryCtx.conditionExpression = entry->condition;
392 entryCtx.constraintCode = entry->constraintData->GetConstraintCode();
393
394 auto clauses = entry->constraintData->GetConstraintClauses( entryCtx );
395
396 for( const wxString& clause : clauses )
397 {
398 if( !clause.IsEmpty() )
399 allClauses.push_back( clause );
400 }
401 }
402 }
403
404 // Build the merged rule
405 wxString rule;
406 rule << wxS( "(rule " ) << DRC_RE_BASE_CONSTRAINT_DATA::formatRuleName( ctx.ruleName )
407 << wxS( "\n" );
408
409 for( const wxString& line : wxSplit( ctx.comment, '\n', '\0' ) )
410 {
411 if( !line.IsEmpty() )
412 rule << wxS( "\t# " ) << line << wxS( "\n" );
413 }
414
415 if( !ctx.layerClause.IsEmpty() )
416 rule << wxS( "\t" ) << ctx.layerClause << wxS( "\n" );
417
418 for( const wxString& clause : allClauses )
419 rule << wxS( "\t" ) << clause << wxS( "\n" );
420
421 if( !ctx.conditionExpression.IsEmpty() )
422 {
423 rule << wxS( "\t(condition \"" )
424 << EscapeString( ctx.conditionExpression, CTX_QUOTED_STR ) << wxS( "\")\n" );
425 }
426
427 // Add severity if any entry has non-default severity
428 for( const auto* entry : aEntries )
429 {
430 if( entry->severity != RPT_SEVERITY_UNDEFINED && entry->severity != RPT_SEVERITY_ERROR )
431 {
432 rule << wxS( "\t" ) << generateSeverityClause( entry->severity ) << wxS( "\n" );
433 break;
434 }
435 }
436
437 rule << wxS( ")" );
438
439 return rule;
440}
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:411
static wxString formatRuleName(const wxString &aRuleName)
Format a rule name for use in S-expression output while preserving the exact name the user chose.
virtual wxString GetConditionPredicate() const
Returns a predicate this panel holds in its own fields rather than in the rule condition,...
virtual wxString GenerateRule(const RULE_GENERATION_CONTEXT &aContext)
wxString generateRuleText(const DRC_RE_LOADED_PANEL_ENTRY &aEntry, const BOARD *aBoard)
Generate the rule text for a single panel entry.
wxString generateMergedRuleText(const std::vector< const DRC_RE_LOADED_PANEL_ENTRY * > &aEntries, const BOARD *aBoard)
Generate a merged rule text from multiple panel entries with the same name/condition.
bool SaveFile(const wxString &aPath, const std::vector< DRC_RE_LOADED_PANEL_ENTRY > &aEntries, const BOARD *aBoard=nullptr, const DRC_RE_FILE_TRIVIA &aTrivia={})
Save all panel entries to a file.
wxString GenerateRulesText(const std::vector< DRC_RE_LOADED_PANEL_ENTRY > &aEntries, const BOARD *aBoard=nullptr, const DRC_RE_FILE_TRIVIA &aTrivia={})
Generate rule text from panel entries.
wxString generateLayerClause(const LSET &aLayers)
Generate a layer clause from an LSET.
wxString generateSeverityClause(SEVERITY aSeverity)
Generate a severity clause.
LSET is a set of PCB_LAYER_IDs.
Definition lset.h:37
static const LSET & ExternalCuMask()
Return a mask holding the Front and Bottom layers.
Definition lset.cpp:630
LSEQ Seq(const LSEQ &aSequence) const
Return an LSEQ from the union of this LSET and a desired sequence.
Definition lset.cpp:309
static LSET AllCuMask(int aCuLayerCount)
Return a mask holding the requested number of Cu PCB_LAYER_IDs.
Definition lset.cpp:595
static const LSET & AllLayersMask()
Definition lset.cpp:637
static const LSET & InternalCuMask()
Return a complete set of internal copper layers which is all Cu layers except F_Cu and B_Cu.
Definition lset.cpp:573
static wxString Name(PCB_LAYER_ID aLayerId)
Return the fixed name association with aLayerId.
Definition lset.cpp:184
wxString GetComment()
Get the comment associated with the rule.
std::string utf8(const wxString &aText)
@ SILK_TO_SILK_CLEARANCE
@ SILK_TO_SOLDERMASK_CLEARANCE
std::string source
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
@ F_SilkS
Definition layer_ids.h:96
@ B_SilkS
Definition layer_ids.h:97
bool AtomicWriteFile(const wxString &aTargetPath, const void *aData, size_t aSize, wxString *aError=nullptr)
Writes aData to aTargetPath via a sibling temp file, fsyncs the data and directory,...
SEVERITY
@ RPT_SEVERITY_WARNING
@ RPT_SEVERITY_ERROR
@ RPT_SEVERITY_UNDEFINED
@ RPT_SEVERITY_EXCLUSION
@ RPT_SEVERITY_IGNORE
wxString EscapeString(const wxString &aSource, ESCAPE_CONTEXT aContext)
The Escape/Unescape routines use HTML-entity-reference-style encoding to handle characters which are:...
@ CTX_QUOTED_STR
The text of a rules file that lies outside every rule, kept so a save can reproduce it.
wxString header
Everything through the version expression, empty for a new file.
std::vector< wxString > leadingTrivia
Comments and blank lines before each rule, by sourceRule.
wxString trailer
Everything after the last rule.
Represents a rule loaded from a .kicad_dru file and mapped to a panel.
wxString ruleName
wxString condition
wxString layerSource
Original layer text: "inner", "outer", or layer name.
LSET layerCondition
std::shared_ptr< DRC_RE_BASE_CONSTRAINT_DATA > constraintData
DRC_RULE_EDITOR_CONSTRAINT_NAME panelType
SEVERITY severity
wxString result
Test unit parsing edge cases and error handling.