|
| 1 | +package checkstyle.checks; |
| 2 | + |
| 3 | +import checkstyle.LintMessage.SeverityLevel; |
| 4 | +import haxeparser.Data; |
| 5 | +import haxe.macro.Expr; |
| 6 | + |
| 7 | +@name("NestedTryDepth") |
| 8 | +@desc("Max number of nested try blocks (default 1)") |
| 9 | +class NestedTryDepthCheck extends Check { |
| 10 | + |
| 11 | + public var severity:String = "ERROR"; |
| 12 | + public var max:Int = 1; |
| 13 | + |
| 14 | + override function _actualRun() { |
| 15 | + for (td in _checker.ast.decls) { |
| 16 | + switch (td.decl) { |
| 17 | + case EClass(d): |
| 18 | + checkFields(d); |
| 19 | + default: |
| 20 | + } |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + function checkFields(d:Definition<ClassFlag, Array<Field>>) { |
| 25 | + for (field in d.data) { |
| 26 | + checkField(field); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + function checkField(f:Field) { |
| 31 | + switch (f.kind) { |
| 32 | + case FFun(fun): |
| 33 | + scanBlock(fun.expr, -1); |
| 34 | + default: |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + function scanBlock(e:Expr, depth:Int) { |
| 39 | + if (e == null) return null; |
| 40 | + if (depth > max) { |
| 41 | + _warnNestedTryDepth(depth, e.pos); |
| 42 | + return; |
| 43 | + } |
| 44 | + switch(e.expr) { |
| 45 | + case EBlock(exprs): |
| 46 | + scanExprs(exprs, depth); |
| 47 | + default: |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + function scanExprs(exprs:Array<Expr>, depth:Int) { |
| 52 | + for (e in exprs) { |
| 53 | + switch(e.expr) { |
| 54 | + case ETry(expr,catches): |
| 55 | + scanBlock(expr, depth + 1); |
| 56 | + scanCatches(catches, depth + 1); |
| 57 | + default: |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + function scanCatches(catches:Array<Catch>, depth:Int) { |
| 63 | + for (c in catches) { |
| 64 | + scanBlock(c.expr, depth); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + function _warnNestedTryDepth(depth:Int, pos:Position) { |
| 69 | + logPos('Nested try depth is $depth (max allowed is ${max})', pos, Reflect.field(SeverityLevel, severity)); |
| 70 | + } |
| 71 | +} |
0 commit comments