KiCad PCB EDA Suite
Loading...
Searching...
No Matches
drc_re_rule_loader.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_loader.h"
21
22#include <base_units.h>
23#include <reporter.h>
25#include <drc/drc_rule_parser.h>
27#include <wx/ffile.h>
28
29#include <algorithm>
30#include <optional>
31#include <tuple>
32#include <utility>
33
48
49
53
54
55double DRC_RULE_LOADER::toMM( int aValue )
56{
57 return aValue / 1000000.0;
58}
59
60
61double DRC_RULE_LOADER::toPS( int aValue )
62{
63 return aValue / pcbIUScale.IU_PER_PS;
64}
65
66
68{
69 for( const DRC_CONSTRAINT& constraint : aRule.m_Constraints )
70 {
71 if( constraint.m_Type == aType )
72 return &constraint;
73 }
74
75 return nullptr;
76}
77
78
79static bool isSymmetricMinOptMax( const DRC_CONSTRAINT* aConstraint )
80{
81 if( !aConstraint )
82 return true;
83
84 const auto& value = aConstraint->GetValue();
85
86 if( !value.HasMin() || !value.HasOpt() || !value.HasMax() )
87 return true;
88
89 return ( value.Opt() - value.Min() ) == ( value.Max() - value.Opt() );
90}
91
92
93// The width and gap panels write min, opt and max around one optimum, so a range missing any of them
94// would be rewritten
95static bool isSymmetricTriple( const DRC_CONSTRAINT* aConstraint )
96{
97 if( !aConstraint )
98 return true;
99
100 const auto& value = aConstraint->GetValue();
101
102 return value.HasMin() && value.HasOpt() && value.HasMax() && isSymmetricMinOptMax( aConstraint );
103}
104
105
106// A panel writes the predicate it holds back as "predicate && rest", so it can only take a
107// condition that is already in that form
108static std::optional<wxString> takeLeadingPredicate( const wxString& aCondition, const wxString& aPredicate )
109{
110 wxString condition = aCondition;
111 condition.Trim( true ).Trim( false );
112
113 if( condition == aPredicate )
114 return wxString();
115
116 wxString rest;
117
118 if( !condition.StartsWith( aPredicate + wxS( " &&" ), &rest ) )
119 return std::nullopt;
120
121 rest.Trim( true ).Trim( false );
122
123 if( rest.IsEmpty() )
124 return std::nullopt;
125
126 return rest;
127}
128
129
130static bool isMinOnly( const DRC_CONSTRAINT* aConstraint )
131{
132 if( !aConstraint )
133 return true;
134
135 const auto& value = aConstraint->GetValue();
136
137 return value.HasMin() && !value.HasOpt() && !value.HasMax();
138}
139
140
141// An absent bound reads back as the largest value of its type, so a panel that writes a bound
142// out cannot be given a range that names only the other end.
143static bool hasBothBounds( const DRC_CONSTRAINT* aConstraint )
144{
145 return !aConstraint || ( aConstraint->GetValue().HasMin() && aConstraint->GetValue().HasMax() );
146}
147
148
149static bool hasMaxBound( const DRC_CONSTRAINT* aConstraint )
150{
151 return !aConstraint || aConstraint->GetValue().HasMax();
152}
153
154
155// The DRC lexer treats a line whose first non-blank character is # as a comment
156static bool isOnCommentLine( const wxString& aContent, size_t aPos )
157{
158 size_t lineStart = aPos == 0 ? wxString::npos : aContent.rfind( '\n', aPos - 1 );
159
160 for( size_t i = ( lineStart == wxString::npos ) ? 0 : lineStart + 1; i <= aPos; ++i )
161 {
162 if( !wxIsspace( aContent[i] ) )
163 return aContent[i] == '#';
164 }
165
166 return false;
167}
168
169
170// Offset of the paren closing the expression opened at aOpen, or npos when unbalanced
171static size_t findClosingParen( const wxString& aContent, size_t aOpen )
172{
173 int parenCount = 0;
174 bool inString = false;
175 bool escaped = false;
176
177 for( size_t i = aOpen; i < aContent.length(); ++i )
178 {
179 wxUniChar c = aContent[i];
180
181 if( escaped )
182 {
183 escaped = false;
184 continue;
185 }
186
187 if( c == '\\' )
188 {
189 escaped = true;
190 continue;
191 }
192
193 if( c == '"' )
194 {
195 inString = !inString;
196 continue;
197 }
198
199 if( inString )
200 continue;
201
202 if( c == '#' && isOnCommentLine( aContent, i ) )
203 {
204 i = aContent.find( '\n', i );
205
206 if( i == wxString::npos )
207 break;
208 }
209 else if( c == '(' )
210 {
211 parenCount++;
212 }
213 else if( c == ')' )
214 {
215 if( --parenCount == 0 )
216 return i;
217 }
218 }
219
220 return wxString::npos;
221}
222
223
224// Span of the next top-level expression at or after aFrom, skipping comments
225static std::pair<size_t, size_t> findNextExpression( const wxString& aContent, size_t aFrom )
226{
227 for( size_t i = aFrom; i < aContent.length(); ++i )
228 {
229 if( aContent[i] == '#' && isOnCommentLine( aContent, i ) )
230 {
231 i = aContent.find( '\n', i );
232
233 if( i == wxString::npos )
234 break;
235 }
236 else if( aContent[i] == '(' )
237 {
238 size_t close = findClosingParen( aContent, i );
239
240 if( close == wxString::npos )
241 break;
242
243 return { i, close + 1 };
244 }
245 }
246
247 return { wxString::npos, wxString::npos };
248}
249
250
251static bool isVersionExpression( const wxString& aContent, size_t aOpen )
252{
253 size_t keyword = aOpen + 1;
254
255 while( keyword < aContent.length() )
256 {
257 if( aContent[keyword] == '#' && isOnCommentLine( aContent, keyword ) )
258 keyword = aContent.find( '\n', keyword );
259 else if( wxIsspace( aContent[keyword] ) )
260 keyword++;
261 else
262 break;
263 }
264
265 return keyword != wxString::npos && aContent.compare( keyword, 7, wxS( "version" ) ) == 0;
266}
267
268
269// Version clauses may repeat anywhere, so the next rule is the next expression that is not one
270static std::pair<size_t, size_t> findNextRule( const wxString& aContent, size_t aFrom )
271{
272 std::pair<size_t, size_t> span = findNextExpression( aContent, aFrom );
273
274 while( span.first != wxString::npos && isVersionExpression( aContent, span.first ) )
275 span = findNextExpression( aContent, span.second );
276
277 return span;
278}
279
280
281// No layer clause means all layers, which an entry stores as an empty set.
282static LSET ruleLayers( const DRC_RULE& aRule )
283{
285 return LSET();
286
287 return aRule.m_LayerCondition;
288}
289
290
291static std::shared_ptr<DRC_RE_BASE_CONSTRAINT_DATA> makeCustomRuleData( const DRC_RULE& aRule )
292{
293 auto customData = std::make_shared<DRC_RE_CUSTOM_RULE_CONSTRAINT_DATA>();
294 customData->SetRuleName( aRule.m_Name );
295 return customData;
296}
297
298
299wxString DRC_RULE_LOADER::ExtractRuleBody( const wxString& aOriginalText )
300{
301 // Comment lines live in the comment field, not in the body.
302 wxArrayString kept;
303
304 for( const wxString& line : wxSplit( aOriginalText, '\n', '\0' ) )
305 {
306 wxString trimmed = line;
307 trimmed.Trim( false );
308
309 if( !trimmed.StartsWith( wxS( "#" ) ) )
310 kept.Add( line );
311 }
312
313 wxString text = wxJoin( kept, '\n', '\0' );
314
315 int ruleKeyword = text.Find( wxS( "rule " ) );
316 if( ruleKeyword == wxNOT_FOUND )
317 return aOriginalText;
318
319 int bodyStart = text.find( '(', ruleKeyword + 5 );
320 if( bodyStart == (int) wxString::npos )
321 return aOriginalText;
322
323 // Take the first clause from the start of its line so it keeps its indent beside the others
324 size_t lineStart = text.rfind( '\n', bodyStart );
325 lineStart = ( lineStart == wxString::npos ) ? 0 : lineStart + 1;
326
327 bool ownLine = text.find_first_not_of( wxS( " \t" ), lineStart ) == (size_t) bodyStart;
328
329 wxString body = text.Mid( ownLine ? lineStart : bodyStart );
330 body.Trim( true );
331
332 if( body.EndsWith( wxS( ")" ) ) )
333 body = body.Left( body.Length() - 1 );
334 body.Trim( true );
335
336 // The body is edited and saved without the indent the lines share; FormatRule puts one back
337 wxArrayString lines = wxSplit( body, '\n', '\0' );
338 std::optional<wxString> indent;
339
340 for( size_t i = ownLine ? 0 : 1; i < lines.size(); ++i )
341 {
342 size_t textStart = lines[i].find_first_not_of( wxS( " \t" ) );
343
344 if( textStart == wxString::npos )
345 continue;
346
347 wxString lead = lines[i].Left( textStart );
348
349 if( !indent )
350 indent = lead;
351
352 size_t common = 0;
353
354 while( common < indent->length() && common < lead.length() && ( *indent )[common] == lead[common] )
355 ++common;
356
357 indent = indent->Left( common );
358 }
359
360 if( !indent || indent->IsEmpty() )
361 return body;
362
363 for( size_t i = ownLine ? 0 : 1; i < lines.size(); ++i )
364 {
365 if( lines[i].StartsWith( *indent ) )
366 lines[i] = lines[i].Mid( indent->length() );
367 }
368
369 return wxJoin( lines, '\n', '\0' );
370}
371
372
373wxString DRC_RULE_LOADER::ExtractRuleComment( const wxString& aOriginalText )
374{
375 wxString comment;
376 wxArrayString lines = wxSplit( aOriginalText, '\n', '\0' );
377
378 for( const wxString& line : lines )
379 {
380 wxString trimmed = line;
381 trimmed.Trim( false );
382
383 if( trimmed.StartsWith( wxS( "#" ) ) )
384 {
385 wxString commentLine = trimmed.Mid( 1 );
386 commentLine.Trim( false );
387
388 if( !comment.IsEmpty() )
389 comment += wxS( "\n" );
390
391 comment += commentLine;
392 }
393 }
394
395 return comment;
396}
397
398
399wxString DRC_RULE_LOADER::cleanStrippedCondition( const wxString& aCondition )
400{
401 wxString cleaned = aCondition;
402
403 // Strip empty parentheses left over from removing conditions
404 wxString prev;
405 do
406 {
407 prev = cleaned;
408 cleaned.Replace( wxS( "()" ), wxS( "" ) );
409 } while( cleaned != prev );
410
411 cleaned.Replace( wxS( "&& &&" ), wxS( "&&" ) );
412 cleaned.Replace( wxS( "|| ||" ), wxS( "||" ) );
413 cleaned.Trim( true ).Trim( false );
414 if( cleaned.StartsWith( wxS( "&&" ) ) )
415 cleaned = cleaned.Mid( 2 ).Trim( false );
416 if( cleaned.EndsWith( wxS( "&&" ) ) )
417 cleaned = cleaned.Left( cleaned.Length() - 2 ).Trim( true );
418 if( cleaned.StartsWith( wxS( "||" ) ) )
419 cleaned = cleaned.Mid( 2 ).Trim( false );
420 if( cleaned.EndsWith( wxS( "||" ) ) )
421 cleaned = cleaned.Left( cleaned.Length() - 2 ).Trim( true );
422
423 return cleaned;
424}
425
426
427std::shared_ptr<DRC_RE_BASE_CONSTRAINT_DATA>
429 const DRC_RULE& aRule,
430 const std::set<DRC_CONSTRAINT_T>& aClaimedConstraints )
431{
432 switch( aPanel )
433 {
434 case VIA_STYLE:
435 {
436 auto data = std::make_shared<DRC_RE_VIA_STYLE_CONSTRAINT_DATA>();
437 data->SetRuleName( aRule.m_Name );
438 data->SetConstraintCode( "via_style" );
439
440 const DRC_CONSTRAINT* viaDia = findConstraint( aRule, VIA_DIAMETER_CONSTRAINT );
441 const DRC_CONSTRAINT* holeSize = findConstraint( aRule, HOLE_SIZE_CONSTRAINT );
442
443 if( viaDia )
444 {
445 data->SetMinViaDiameter( toMM( viaDia->GetValue().Min() ) );
446
447 if( viaDia->GetValue().HasMax() )
448 data->SetMaxViaDiameter( toMM( viaDia->GetValue().Max() ) );
449
450 if( viaDia->GetValue().HasOpt() )
451 data->SetOptViaDiameter( toMM( viaDia->GetValue().Opt() ) );
452 }
453
454 if( holeSize )
455 {
456 data->SetMinViaHoleSize( toMM( holeSize->GetValue().Min() ) );
457
458 if( holeSize->GetValue().HasMax() )
459 data->SetMaxViaHoleSize( toMM( holeSize->GetValue().Max() ) );
460
461 if( holeSize->GetValue().HasOpt() )
462 data->SetOptViaHoleSize( toMM( holeSize->GetValue().Opt() ) );
463 }
464
465 wxString condition = aRule.m_Condition ? aRule.m_Condition->GetExpression() : wxString();
466
467 if( condition.Contains( wxS( "Via_Type" ) ) )
468 {
469 std::optional<wxString> rest;
470
471 for( VIA_STYLE_TYPE type :
473 {
474 data->SetViaType( type );
475 rest = takeLeadingPredicate( condition, data->GetConditionPredicate() );
476
477 if( rest )
478 break;
479 }
480
481 // The panel's choice cannot write back any other via type test
482 if( !rest )
483 return makeCustomRuleData( aRule );
484
485 condition = *rest;
486 }
487
488 data->SetRuleCondition( condition );
489
490 return data;
491 }
492
494 {
495 const DRC_CONSTRAINT* trackWidth = findConstraint( aRule, TRACK_WIDTH_CONSTRAINT );
496 const DRC_CONSTRAINT* diffGap = findConstraint( aRule, DIFF_PAIR_GAP_CONSTRAINT );
497 const DRC_CONSTRAINT* uncoupled = findConstraint( aRule, MAX_UNCOUPLED_CONSTRAINT );
498
499 if( !isSymmetricTriple( trackWidth ) || !isSymmetricTriple( diffGap ) || !hasMaxBound( uncoupled ) )
500 return makeCustomRuleData( aRule );
501
502 auto data = std::make_shared<DRC_RE_ROUTING_DIFF_PAIR_CONSTRAINT_DATA>();
503 data->SetRuleName( aRule.m_Name );
504 data->SetConstraintCode( "diff_pair_gap" );
505
506 if( trackWidth )
507 {
508 double opt = toMM( trackWidth->GetValue().PinnedOpt() );
509 double min = toMM( trackWidth->GetValue().Min() );
510
511 data->SetOptWidth( opt );
512 data->SetWidthTolerance( opt - min );
513 }
514
515 if( diffGap )
516 {
517 double opt = toMM( diffGap->GetValue().PinnedOpt() );
518 double min = toMM( diffGap->GetValue().Min() );
519
520 data->SetOptGap( opt );
521 data->SetGapTolerance( opt - min );
522 }
523
524 if( uncoupled )
525 {
526 data->SetMaxUncoupledLength( toMM( uncoupled->GetValue().Max() ) );
527 }
528
529 return data;
530 }
531
533 {
534 const DRC_CONSTRAINT* textHeight = findConstraint( aRule, TEXT_HEIGHT_CONSTRAINT );
535 const DRC_CONSTRAINT* textThickness = findConstraint( aRule, LINE_WIDTH_CONSTRAINT );
536
537 // The panel saves only minimums, so a max or opt would be lost on edit
538 if( !isMinOnly( textHeight ) || !isMinOnly( textThickness ) )
539 return makeCustomRuleData( aRule );
540
541 auto data = std::make_shared<DRC_RE_MINIMUM_TEXT_HEIGHT_THICKNESS_CONSTRAINT_DATA>();
542 data->SetRuleName( aRule.m_Name );
543 data->SetConstraintCode( "text_height" );
544
545 if( textHeight )
546 data->SetMinTextHeight( toMM( textHeight->GetValue().Min() ) );
547
548 if( textThickness )
549 data->SetMinTextThickness( toMM( textThickness->GetValue().Min() ) );
550
551 return data;
552 }
553
554 case ROUTING_WIDTH:
555 {
556 const DRC_CONSTRAINT* trackWidth = findConstraint( aRule, TRACK_WIDTH_CONSTRAINT );
557
558 if( !isSymmetricTriple( trackWidth ) )
559 return makeCustomRuleData( aRule );
560
561 auto data = std::make_shared<DRC_RE_ROUTING_WIDTH_CONSTRAINT_DATA>();
562 data->SetRuleName( aRule.m_Name );
563 data->SetConstraintCode( "track_width" );
564
565 if( trackWidth )
566 {
567 double opt = toMM( trackWidth->GetValue().PinnedOpt() );
568 double min = toMM( trackWidth->GetValue().Min() );
569
570 data->SetOptWidth( opt );
571 data->SetWidthTolerance( opt - min );
572 }
573
574 return data;
575 }
576
577 case ABSOLUTE_LENGTH:
578 {
579 const DRC_CONSTRAINT* length = findConstraint( aRule, LENGTH_CONSTRAINT );
580
581 if( !isSymmetricMinOptMax( length ) || !hasBothBounds( length ) )
582 return makeCustomRuleData( aRule );
583
584 auto data = std::make_shared<DRC_RE_ABSOLUTE_LENGTH_TWO_CONSTRAINT_DATA>();
585 data->SetRuleName( aRule.m_Name );
586 data->SetConstraintCode( "length" );
587
588 if( length )
589 {
590 bool timeDomain = length->GetOption( DRC_CONSTRAINT::OPTIONS::TIME_DOMAIN );
591
592 auto convert = [&]( int aValue )
593 {
594 return timeDomain ? toPS( aValue ) : toMM( aValue );
595 };
596
597 double min = convert( length->GetValue().Min() );
598 double max = convert( length->GetValue().Max() );
599
600 // A rule without an optimum gets the window center, so saving keeps its min and max.
601 double opt = length->GetValue().HasOpt() ? convert( length->GetValue().PinnedOpt() ) : ( min + max ) / 2.0;
602
603 data->SetTimeDomain( timeDomain );
604 data->SetOptimumLength( opt );
605 data->SetTolerance( ( max - min ) / 2.0 );
606 }
607
608 return data;
609 }
610
612 {
613 const DRC_CONSTRAINT* length = findConstraint( aRule, LENGTH_CONSTRAINT );
614 const DRC_CONSTRAINT* skew = findConstraint( aRule, SKEW_CONSTRAINT );
615
616 if( !isSymmetricMinOptMax( length ) || !hasBothBounds( length ) || !hasMaxBound( skew ) )
617 return makeCustomRuleData( aRule );
618
619 auto data = std::make_shared<DRC_RE_MATCHED_LENGTH_DIFF_PAIR_CONSTRAINT_DATA>();
620 data->SetRuleName( aRule.m_Name );
621 data->SetConstraintCode( "length" );
622
623 if( length )
624 {
625 double minMM = toMM( length->GetValue().Min() );
626 double maxMM = toMM( length->GetValue().Max() );
627
628 // A rule without an optimum gets the window center, so saving keeps its min and max
629 double optMM = length->GetValue().HasOpt() ? toMM( length->GetValue().PinnedOpt() )
630 : ( minMM + maxMM ) / 2.0;
631
632 data->SetOptimumLength( optMM );
633 data->SetTolerance( ( maxMM - minMM ) / 2.0 );
634 }
635
636 if( skew )
637 {
638 data->SetMaxSkew( toMM( skew->GetValue().Max() ) );
639 data->SetWithinDiffPairs( skew->GetOption( DRC_CONSTRAINT::OPTIONS::SKEW_WITHIN_DIFF_PAIRS ) );
640 }
641
642 return data;
643 }
644
645 case PERMITTED_LAYERS:
646 {
647 auto data = std::make_shared<DRC_RE_PERMITTED_LAYERS_CONSTRAINT_DATA>();
648 data->SetRuleName( aRule.m_Name );
649
650 const DRC_CONSTRAINT* constraint = findConstraint( aRule, ASSERTION_CONSTRAINT );
651
652 if( constraint && constraint->m_Test )
653 {
654 wxString expr = constraint->m_Test->GetExpression();
655
656 data->SetTopLayerEnabled( expr.Contains( wxS( "F.Cu" ) ) );
657 data->SetBottomLayerEnabled( expr.Contains( wxS( "B.Cu" ) ) );
658
659 // Check for layer references the panel can't represent
660 wxString remaining = expr;
661 remaining.Replace( wxS( "A.Layer == 'F.Cu'" ), wxS( "" ) );
662 remaining.Replace( wxS( "A.Layer == 'B.Cu'" ), wxS( "" ) );
663
664 if( remaining.Contains( wxS( "A.Layer" ) ) )
665 {
666 // Inner or non-standard layers — fall back to custom rule
667 auto customData = std::make_shared<DRC_RE_CUSTOM_RULE_CONSTRAINT_DATA>();
668 customData->SetRuleName( aRule.m_Name );
669 return customData;
670 }
671 }
672
673 return data;
674 }
675
677 {
678 auto data = std::make_shared<DRC_RE_ALLOWED_ORIENTATION_CONSTRAINT_DATA>();
679 data->SetRuleName( aRule.m_Name );
680 data->SetConstraintCode( wxS( "allowed_orientation" ) );
681
682 const DRC_CONSTRAINT* constraint = findConstraint( aRule, ASSERTION_CONSTRAINT );
683
684 if( constraint && constraint->m_Test )
685 {
686 wxString expr = constraint->m_Test->GetExpression();
687
688 data->SetIsZeroDegreesAllowed( expr.Contains( wxS( "== 0 deg" ) ) );
689 data->SetIsNinetyDegreesAllowed( expr.Contains( wxS( "== 90 deg" ) ) );
690 data->SetIsOneEightyDegreesAllowed( expr.Contains( wxS( "== 180 deg" ) ) );
691 data->SetIsTwoSeventyDegreesAllowed( expr.Contains( wxS( "== 270 deg" ) ) );
692
693 if( data->GetIsZeroDegreesAllowed() && data->GetIsNinetyDegreesAllowed()
694 && data->GetIsOneEightyDegreesAllowed() && data->GetIsTwoSeventyDegreesAllowed() )
695 {
696 data->SetIsAllDegreesAllowed( true );
697 return data;
698 }
699
700 if( data->GetIsZeroDegreesAllowed() || data->GetIsNinetyDegreesAllowed()
701 || data->GetIsOneEightyDegreesAllowed() || data->GetIsTwoSeventyDegreesAllowed() )
702 {
703 return data;
704 }
705
706 // Non-standard angles cannot be represented by the
707 // orientation panel, fall back to custom rule
708 auto customData = std::make_shared<DRC_RE_CUSTOM_RULE_CONSTRAINT_DATA>();
709 customData->SetRuleName( aRule.m_Name );
710 return customData;
711 }
712 else
713 {
714 data->SetIsAllDegreesAllowed( true );
715 }
716
717 return data;
718 }
719
720 case VIAS_UNDER_SMD:
721 {
722 auto data = std::make_shared<DRC_RE_VIAS_UNDER_SMD_CONSTRAINT_DATA>();
723 data->SetRuleName( aRule.m_Name );
724 data->SetConstraintCode( wxS( "disallow_via" ) );
725
726 std::optional<wxString> rest = takeLeadingPredicate(
727 aRule.m_Condition ? aRule.m_Condition->GetExpression() : wxString(), data->GetConditionPredicate() );
728
729 if( !rest )
730 return makeCustomRuleData( aRule );
731
732 data->SetRuleCondition( *rest );
733
734 const DRC_CONSTRAINT* constraint = findConstraint( aRule, DISALLOW_CONSTRAINT );
735
736 if( constraint )
737 {
738 data->SetDisallowThroughVias( ( constraint->m_DisallowFlags & DRC_DISALLOW_THROUGH_VIAS ) != 0 );
739 data->SetDisallowMicroVias( ( constraint->m_DisallowFlags & DRC_DISALLOW_MICRO_VIAS ) != 0 );
740 data->SetDisallowBlindVias( ( constraint->m_DisallowFlags & DRC_DISALLOW_BLIND_VIAS ) != 0 );
741 data->SetDisallowBuriedVias( ( constraint->m_DisallowFlags & DRC_DISALLOW_BURIED_VIAS ) != 0 );
742 }
743
744 return data;
745 }
746
747 case CUSTOM_RULE:
748 {
749 auto data = std::make_shared<DRC_RE_CUSTOM_RULE_CONSTRAINT_DATA>();
750 data->SetRuleName( aRule.m_Name );
751 return data;
752 }
753
754 default:
755 {
756 // For numeric input types, create a generic numeric constraint data
758 {
760 data->SetRuleName( aRule.m_Name );
761
762 wxString code = DRC_RULE_EDITOR_UTILS::GetConstraintCode( aPanel );
763 data->SetConstraintCode( code );
764
765 // Find the first matching constraint from the claimed set
766 for( DRC_CONSTRAINT_T type : aClaimedConstraints )
767 {
768 const DRC_CONSTRAINT* constraint = findConstraint( aRule, type );
769
770 if( constraint )
771 {
773 data->SetNumericInputValue( constraint->GetValue().Max() );
774 else if( type == HOLE_ASPECT_RATIO_CONSTRAINT )
775 data->SetNumericInputValue( constraint->GetValue().Max() / 1000.0 );
776 else if( type == MIN_RESOLVED_SPOKES_CONSTRAINT )
777 data->SetNumericInputValue( constraint->GetValue().Min() );
778 else
779 data->SetNumericInputValue( toMM( constraint->GetValue().Min() ) );
780
781 break;
782 }
783 }
784
785 return data;
786 }
787
788 // Fallback to custom rule
789 auto data = std::make_shared<DRC_RE_CUSTOM_RULE_CONSTRAINT_DATA>();
790 data->SetRuleName( aRule.m_Name );
791 return data;
792 }
793 }
794}
795
796
797std::vector<DRC_RE_LOADED_PANEL_ENTRY> DRC_RULE_LOADER::LoadRule( const DRC_RULE& aRule,
798 const wxString& aOriginalText )
799{
800 std::vector<DRC_RE_LOADED_PANEL_ENTRY> entries;
801
802 // Get condition expression if present
803 wxString condition;
804
805 if( aRule.m_Condition )
806 condition = aRule.m_Condition->GetExpression();
807
808 // Only the absolute length panel can hold time domain values.
809 bool fitsStructuredPanels = true;
810
811 for( const DRC_CONSTRAINT& constraint : aRule.m_Constraints )
812 {
814 && !( constraint.m_Type == LENGTH_CONSTRAINT && aRule.m_Constraints.size() == 1 ) )
815 {
816 fitsStructuredPanels = false;
817 break;
818 }
819 }
820
821 // Match the rule to panels
822 std::vector<DRC_PANEL_MATCH> matches;
823
824 if( fitsStructuredPanels )
825 matches = m_matcher.MatchRule( aRule );
826
827 for( DRC_PANEL_MATCH& match : matches )
828 {
829 if( match.panelType == PERMITTED_LAYERS && match.claimedConstraints.count( ASSERTION_CONSTRAINT ) )
830 {
831 const DRC_CONSTRAINT* assertion = findConstraint( aRule, ASSERTION_CONSTRAINT );
832
833 if( assertion && assertion->m_Test )
834 {
835 wxString expr = assertion->m_Test->GetExpression();
836
837 if( expr.Contains( wxS( "Orientation" ) ) && !expr.Contains( wxS( "Layer" ) ) )
838 match.panelType = ALLOWED_ORIENTATION;
839 }
840 }
841
842 if( match.panelType == SILK_TO_SILK_CLEARANCE && match.claimedConstraints.count( SILK_CLEARANCE_CONSTRAINT ) )
843 {
844 if( !condition.IsEmpty()
845 && ( condition.Contains( wxS( "L == 'F.Mask'" ) ) || condition.Contains( wxS( "L == 'B.Mask'" ) ) ) )
846 {
847 match.panelType = SILK_TO_SOLDERMASK_CLEARANCE;
848 }
849 else if( !condition.IsEmpty() && !condition.Contains( wxS( "L == 'F.SilkS'" ) )
850 && !condition.Contains( wxS( "L == 'B.SilkS'" ) ) )
851 {
852 match.panelType = CUSTOM_RULE;
853 }
854 }
855
856 auto constraintData = createConstraintData( match.panelType, aRule, match.claimedConstraints );
857
858 if( !constraintData )
859 continue;
860
861 // If createConstraintData returned a custom rule fallback (e.g. non-standard
862 // orientation angles), update the panel type to match the actual data type
863 auto customFallback = std::dynamic_pointer_cast<DRC_RE_CUSTOM_RULE_CONSTRAINT_DATA>( constraintData );
864
865 if( customFallback && match.panelType != CUSTOM_RULE )
866 {
867 match.panelType = CUSTOM_RULE;
868 }
869
870 if( match.panelType == SILK_TO_SOLDERMASK_CLEARANCE )
871 {
872 wxString cleanedCondition = condition;
873
874 // New format: L == 'F.Mask' || L == 'B.Mask'
875 bool hasBothSides = condition.Contains( wxS( "L == 'F.Mask' || L == 'B.Mask'" ) );
876
877 if( hasBothSides )
878 {
879 constraintData->SetLayers( { F_SilkS, B_SilkS } );
880 constraintData->SetLayerSource( wxS( "" ) );
881
882 cleanedCondition.Replace( wxS( "L == 'F.Mask' || L == 'B.Mask'" ), wxS( "" ) );
883 }
884 else
885 {
886 bool isFront = condition.Contains( wxS( "F.Mask" ) );
887 PCB_LAYER_ID layer = isFront ? F_SilkS : B_SilkS;
888 constraintData->SetLayers( { layer } );
889 constraintData->SetLayerSource( isFront ? wxS( "F.SilkS" ) : wxS( "B.SilkS" ) );
890
891 cleanedCondition.Replace( wxS( "L == 'F.Mask'" ), wxS( "" ) );
892 cleanedCondition.Replace( wxS( "L == 'B.Mask'" ), wxS( "" ) );
893 }
894
895 constraintData->SetRuleCondition( cleanStrippedCondition( cleanedCondition ) );
896 }
897
898 if( match.panelType == SILK_TO_SILK_CLEARANCE )
899 {
900 wxString cleanedCondition = condition;
901
902 bool hasBothSides = condition.Contains( wxS( "L == 'F.SilkS' || L == 'B.SilkS'" ) );
903
904 if( hasBothSides )
905 {
906 constraintData->SetLayers( { F_SilkS, B_SilkS } );
907 constraintData->SetLayerSource( wxS( "" ) );
908
909 cleanedCondition.Replace( wxS( "L == 'F.SilkS' || L == 'B.SilkS'" ), wxS( "" ) );
910 }
911 else if( condition.Contains( wxS( "L == 'F.SilkS'" ) ) || condition.Contains( wxS( "L == 'B.SilkS'" ) ) )
912 {
913 bool isFront = condition.Contains( wxS( "F.SilkS" ) );
914 PCB_LAYER_ID layer = isFront ? F_SilkS : B_SilkS;
915 constraintData->SetLayers( { layer } );
916 constraintData->SetLayerSource( isFront ? wxS( "F.SilkS" ) : wxS( "B.SilkS" ) );
917
918 cleanedCondition.Replace( wxS( "L == 'F.SilkS'" ), wxS( "" ) );
919 cleanedCondition.Replace( wxS( "L == 'B.SilkS'" ), wxS( "" ) );
920 }
921
922 constraintData->SetRuleCondition( cleanStrippedCondition( cleanedCondition ) );
923 }
924
925 if( match.panelType == CUSTOM_RULE && customFallback )
926 {
927 customFallback->SetRuleText( ExtractRuleBody( aOriginalText ) );
928 }
929
930 if( match.panelType != VIA_STYLE && match.panelType != SILK_TO_SOLDERMASK_CLEARANCE
931 && match.panelType != SILK_TO_SILK_CLEARANCE && match.panelType != VIAS_UNDER_SMD )
932 constraintData->SetRuleCondition( condition );
933
934 // The silk branches above moved the side of the board out of the condition and into the
935 // layers they own, so the entry takes what they wrote, not the text it was parsed from
936 bool stripped = match.panelType == SILK_TO_SOLDERMASK_CLEARANCE || match.panelType == SILK_TO_SILK_CLEARANCE;
937
938 wxString entryCondition = stripped ? constraintData->GetRuleCondition() : condition;
939 LSET entryLayers = stripped ? LSET( constraintData->GetLayers() ) : ruleLayers( aRule );
940
941 DRC_RE_LOADED_PANEL_ENTRY entry( match.panelType, constraintData, aRule.m_Name, entryCondition,
942 aRule.m_Severity, entryLayers );
943
944 // Preserve original layer source text for round-trip fidelity
945 wxString source = aRule.m_LayerSource;
946 if( source.StartsWith( wxS( "'" ) ) && source.EndsWith( wxS( "'" ) ) )
947 source = source.Mid( 1, source.Length() - 2 );
948
949 entry.layerSource = stripped ? constraintData->GetLayerSource() : source;
950
951 wxString comment = ExtractRuleComment( aOriginalText );
952 if( !comment.IsEmpty() )
953 constraintData->SetComment( comment );
954
955 // Store original text only for the first entry to avoid duplication issues
956 if( entries.empty() )
957 entry.originalRuleText = aOriginalText;
958
959 entries.push_back( std::move( entry ) );
960 }
961
962 // Text holds the whole rule body, so beside a panel entry it would drop or revive clauses on save,
963 // and a predicate one part took out of the shared condition would leave it for the other parts
964 if( entries.size() > 1
965 && std::any_of( entries.begin(), entries.end(),
966 []( const DRC_RE_LOADED_PANEL_ENTRY& aEntry )
967 {
968 return aEntry.panelType == CUSTOM_RULE
969 || !aEntry.constraintData->GetConditionPredicate().IsEmpty();
970 } ) )
971 {
972 entries.clear();
973 }
974
975 // If no matches, create a custom rule entry
976 if( entries.empty() )
977 {
978 auto customData = std::make_shared<DRC_RE_CUSTOM_RULE_CONSTRAINT_DATA>();
979 customData->SetRuleName( aRule.m_Name );
980 customData->SetRuleCondition( condition );
981
982 wxString comment = ExtractRuleComment( aOriginalText );
983 if( !comment.IsEmpty() )
984 customData->SetComment( comment );
985
986 customData->SetRuleText( ExtractRuleBody( aOriginalText ) );
987
988 DRC_RE_LOADED_PANEL_ENTRY entry( CUSTOM_RULE, customData, aRule.m_Name, condition, aRule.m_Severity,
989 ruleLayers( aRule ) );
990 wxString source = aRule.m_LayerSource;
991 if( source.StartsWith( wxS( "'" ) ) && source.EndsWith( wxS( "'" ) ) )
992 source = source.Mid( 1, source.Length() - 2 );
993 entry.layerSource = source;
994 entry.originalRuleText = aOriginalText;
995 entries.push_back( std::move( entry ) );
996 }
997
998 for( DRC_RE_LOADED_PANEL_ENTRY& entry : entries )
999 entry.originalEntryCount = static_cast<int>( entries.size() );
1000
1001 return entries;
1002}
1003
1004
1005std::vector<DRC_RE_LOADED_PANEL_ENTRY> DRC_RULE_LOADER::LoadFromString( const wxString& aRulesText, bool* aParsed )
1006{
1007 std::vector<DRC_RE_LOADED_PANEL_ENTRY> allEntries;
1008 std::vector<std::shared_ptr<DRC_RULE>> parsedRules;
1009
1011
1012 wxString rulesText = aRulesText;
1013 auto [start, end] = findNextExpression( rulesText, 0 );
1014
1015 if( start == wxString::npos || !isVersionExpression( rulesText, start ) )
1016 {
1017 rulesText.Prepend( "(version 2)\n" );
1018 std::tie( start, end ) = findNextExpression( rulesText, 0 );
1019 }
1020
1021 try
1022 {
1023 DRC_RULES_PARSER parser( rulesText, "Rule Loader" );
1024 parser.Parse( parsedRules, nullptr );
1025 }
1026 catch( const IO_ERROR& )
1027 {
1028 if( aParsed )
1029 *aParsed = false;
1030
1031 return allEntries;
1032 }
1033
1034 if( aParsed )
1035 *aParsed = true;
1036
1037 // The parser accepted the text, so its non-version expressions are the rules in parse order
1038 // and everything between them is kept verbatim for the saver
1039 size_t pos = end;
1040 m_fileTrivia.header = rulesText.Left( pos );
1041
1042 int ruleIndex = 0;
1043
1044 for( const auto& rule : parsedRules )
1045 {
1046 wxString originalText;
1047 wxString leadingTrivia;
1048
1049 std::tie( start, end ) = findNextRule( rulesText, pos );
1050
1051 if( start != wxString::npos )
1052 {
1053 originalText = rulesText.Mid( start, end - start );
1054 leadingTrivia = rulesText.Mid( pos, start - pos );
1055 pos = end;
1056 }
1057
1058 m_fileTrivia.leadingTrivia.push_back( leadingTrivia );
1059
1060 std::vector<DRC_RE_LOADED_PANEL_ENTRY> ruleEntries = LoadRule( *rule, originalText );
1061
1062 for( auto& entry : ruleEntries )
1063 {
1064 entry.sourceRule = ruleIndex;
1065 entry.ruleGroupId = ruleIndex + 1;
1066 allEntries.push_back( std::move( entry ) );
1067 }
1068
1069 ruleIndex++;
1070 }
1071
1072 m_fileTrivia.trailer = rulesText.Mid( pos );
1073
1074 return allEntries;
1075}
1076
1077
1078wxString DRC_RULE_LOADER::ExtractRuleText( const wxString& aContent, const wxString& aRuleName )
1079{
1080 // Search for the rule by name, handling both quoted and unquoted names.
1081 // The quoted form includes the closing quote as a boundary so partial
1082 // matches like "Clearance" vs "Clearance for BGA" are not possible.
1083 // The unquoted form needs an explicit boundary check.
1084 wxString quotedSearch = wxString::Format( wxS( "(rule \"%s\"" ), aRuleName );
1085 wxString unquotedSearch = wxString::Format( wxS( "(rule %s" ), aRuleName );
1086
1087 size_t startPos = aContent.find( quotedSearch );
1088
1089 if( startPos == wxString::npos )
1090 {
1091 size_t pos = 0;
1092
1093 while( ( pos = aContent.find( unquotedSearch, pos ) ) != wxString::npos )
1094 {
1095 size_t afterMatch = pos + unquotedSearch.length();
1096
1097 if( afterMatch >= aContent.length()
1098 || aContent[afterMatch] == ')'
1099 || aContent[afterMatch] == ' '
1100 || aContent[afterMatch] == '\n'
1101 || aContent[afterMatch] == '\r'
1102 || aContent[afterMatch] == '\t' )
1103 {
1104 startPos = pos;
1105 break;
1106 }
1107
1108 pos = afterMatch;
1109 }
1110 }
1111
1112 if( startPos == wxString::npos )
1113 return wxEmptyString;
1114
1115 size_t endPos = findClosingParen( aContent, startPos );
1116
1117 if( endPos == wxString::npos )
1118 return wxEmptyString;
1119
1120 return aContent.Mid( startPos, endPos - startPos + 1 );
1121}
1122
1123
1124std::vector<DRC_RE_LOADED_PANEL_ENTRY> DRC_RULE_LOADER::LoadFile( const wxString& aPath )
1125{
1126 std::vector<DRC_RE_LOADED_PANEL_ENTRY> allEntries;
1127
1129
1130 wxFFile file( aPath, "r" );
1131
1132 if( !file.IsOpened() )
1133 return allEntries;
1134
1135 wxString content;
1136 file.ReadAll( &content );
1137 file.Close();
1138
1139 return LoadFromString( content );
1140}
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:128
DRC_RULE_CONDITION * m_Test
Definition drc_rule.h:209
int m_DisallowFlags
Definition drc_rule.h:207
const MINOPTMAX< int > & GetValue() const
Definition drc_rule.h:129
DRC_CONSTRAINT_T m_Type
Definition drc_rule.h:205
bool GetOption(OPTIONS option) const
Definition drc_rule.h:193
void Parse(std::vector< std::shared_ptr< DRC_RULE > > &aRules, REPORTER *aReporter)
wxString GetExpression() const
static bool IsNumericInputType(const DRC_RULE_EDITOR_CONSTRAINT_NAME &aConstraintType)
static wxString GetConstraintCode(DRC_RULE_EDITOR_CONSTRAINT_NAME aConstraintType)
Translate a rule tree node type into the keyword used by the rules file for that constraint.
static std::shared_ptr< DRC_RE_NUMERIC_INPUT_CONSTRAINT_DATA > CreateNumericConstraintData(DRC_RULE_EDITOR_CONSTRAINT_NAME aType)
double toMM(int aValue)
Convert internal units (nanometers) to millimeters.
DRC_RE_FILE_TRIVIA m_fileTrivia
DRC_PANEL_MATCHER m_matcher
std::vector< DRC_RE_LOADED_PANEL_ENTRY > LoadRule(const DRC_RULE &aRule, const wxString &aOriginalText)
Load a single DRC_RULE and convert it to panel entries.
double toPS(int aValue)
Convert internal time units to picoseconds.
std::vector< DRC_RE_LOADED_PANEL_ENTRY > LoadFromString(const wxString &aRulesText, bool *aParsed=nullptr)
Load rules from a text string.
const DRC_CONSTRAINT * findConstraint(const DRC_RULE &aRule, DRC_CONSTRAINT_T aType)
Find a constraint of a specific type in a rule.
static wxString ExtractRuleComment(const wxString &aOriginalText)
Extract comment lines from a rule.
static wxString ExtractRuleBody(const wxString &aOriginalText)
Extract the body of a rule from its original text, stripping the (rule "name" ...) wrapper.
static wxString ExtractRuleText(const wxString &aContent, const wxString &aRuleName)
Extract the complete original text of a rule from file content.
std::vector< DRC_RE_LOADED_PANEL_ENTRY > LoadFile(const wxString &aPath)
Load all rules from a .kicad_dru file.
wxString cleanStrippedCondition(const wxString &aCondition)
Clean up a condition string after auto-generated tokens have been removed.
std::shared_ptr< DRC_RE_BASE_CONSTRAINT_DATA > createConstraintData(DRC_RULE_EDITOR_CONSTRAINT_NAME aPanel, const DRC_RULE &aRule, const std::set< DRC_CONSTRAINT_T > &aClaimedConstraints)
Create the appropriate constraint data object for a panel type.
SEVERITY m_Severity
Definition drc_rule.h:86
DRC_RULE_CONDITION * m_Condition
Definition drc_rule.h:84
LSET m_LayerCondition
Definition drc_rule.h:83
std::vector< DRC_CONSTRAINT > m_Constraints
Definition drc_rule.h:85
wxString m_Name
Definition drc_rule.h:80
wxString m_LayerSource
Definition drc_rule.h:82
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
LSET is a set of PCB_LAYER_IDs.
Definition lset.h:37
static const LSET & AllLayersMask()
Definition lset.cpp:637
T Min() const
Definition minoptmax.h:29
bool HasMax() const
Definition minoptmax.h:38
T PinnedOpt() const
Definition minoptmax.h:32
bool HasMin() const
Definition minoptmax.h:37
T Max() const
Definition minoptmax.h:30
T Opt() const
Definition minoptmax.h:31
bool HasOpt() const
Definition minoptmax.h:39
@ DRC_DISALLOW_BURIED_VIAS
@ DRC_DISALLOW_BLIND_VIAS
@ DRC_DISALLOW_THROUGH_VIAS
@ DRC_DISALLOW_MICRO_VIAS
@ VIA_DIAMETER_CONSTRAINT
@ DIFF_PAIR_GAP_CONSTRAINT
@ DISALLOW_CONSTRAINT
@ TRACK_WIDTH_CONSTRAINT
@ SILK_CLEARANCE_CONSTRAINT
@ MIN_RESOLVED_SPOKES_CONSTRAINT
@ HOLE_ASPECT_RATIO_CONSTRAINT
@ LENGTH_CONSTRAINT
@ VIA_COUNT_CONSTRAINT
@ MAX_UNCOUPLED_CONSTRAINT
@ ASSERTION_CONSTRAINT
@ SKEW_CONSTRAINT
@ LINE_WIDTH_CONSTRAINT
@ MICROVIA_STACK_DEPTH_CONSTRAINT
@ HOLE_SIZE_CONSTRAINT
@ TEXT_HEIGHT_CONSTRAINT
static std::shared_ptr< DRC_RE_BASE_CONSTRAINT_DATA > makeCustomRuleData(const DRC_RULE &aRule)
static std::pair< size_t, size_t > findNextExpression(const wxString &aContent, size_t aFrom)
static bool isOnCommentLine(const wxString &aContent, size_t aPos)
static bool hasBothBounds(const DRC_CONSTRAINT *aConstraint)
static size_t findClosingParen(const wxString &aContent, size_t aOpen)
static bool hasMaxBound(const DRC_CONSTRAINT *aConstraint)
static bool isVersionExpression(const wxString &aContent, size_t aOpen)
static std::pair< size_t, size_t > findNextRule(const wxString &aContent, size_t aFrom)
static bool isMinOnly(const DRC_CONSTRAINT *aConstraint)
static bool isSymmetricMinOptMax(const DRC_CONSTRAINT *aConstraint)
static bool isSymmetricTriple(const DRC_CONSTRAINT *aConstraint)
static std::optional< wxString > takeLeadingPredicate(const wxString &aCondition, const wxString &aPredicate)
static LSET ruleLayers(const DRC_RULE &aRule)
DRC_RULE_EDITOR_CONSTRAINT_NAME
@ ALLOWED_ORIENTATION
@ SILK_TO_SILK_CLEARANCE
@ ROUTING_DIFF_PAIR
@ SILK_TO_SOLDERMASK_CLEARANCE
@ VIAS_UNDER_SMD
@ ABSOLUTE_LENGTH
@ PERMITTED_LAYERS
@ MINIMUM_TEXT_HEIGHT_AND_THICKNESS
@ ROUTING_WIDTH
@ MATCHED_LENGTH_DIFF_PAIR
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
Result of matching a panel to constraints.
The text of a rules file that lies outside every rule, kept so a save can reproduce it.
Represents a rule loaded from a .kicad_dru file and mapped to a panel.
wxString originalRuleText
wxString layerSource
Original layer text: "inner", "outer", or layer name.
VECTOR2I end