// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.java.decompiler.code.cfg;

import org.jetbrains.java.decompiler.main.DecompilerContext;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class ExceptionRangeCFG {
  private final List<BasicBlock> protectedRange; // FIXME: replace with set
  private BasicBlock handler;
  private List<String> exceptionTypes;

  public ExceptionRangeCFG(List<BasicBlock> protectedRange, BasicBlock handler, List<String> exceptionType) {
    this.protectedRange = protectedRange;
    this.handler = handler;

    if (exceptionType != null) {
      this.exceptionTypes = new ArrayList<>(exceptionType);
    }
  }

  public boolean isCircular() {
    return protectedRange.contains(handler);
  }

  @Override
  public String toString() {
    String new_line_separator = DecompilerContext.getNewLineSeparator();
    StringBuilder buf = new StringBuilder();

    buf.append("exceptionType:");
    for (String exception_type : exceptionTypes) {
      buf.append(" ").append(exception_type);
    }
    buf.append(new_line_separator);

    buf.append("handler: ").append(handler.id).append(new_line_separator);
    buf.append("range: ");
    for (BasicBlock block : protectedRange) {
      buf.append(block.id).append(" ");
    }
    buf.append(new_line_separator);

    return buf.toString();
  }

  public BasicBlock getHandler() {
    return handler;
  }

  public void setHandler(BasicBlock handler) {
    this.handler = handler;
  }

  public List<BasicBlock> getProtectedRange() {
    return protectedRange;
  }

  public List<String> getExceptionTypes() {
    return this.exceptionTypes;
  }

  public void addExceptionType(String exceptionType) {
    if (this.exceptionTypes == null) {
      return;
    }

    if (exceptionType == null) {
      this.exceptionTypes = null;
    }
    else {
      this.exceptionTypes.add(exceptionType);
    }
  }

  public String getUniqueExceptionsString() {
    return exceptionTypes != null ? exceptionTypes.stream().distinct().collect(Collectors.joining(":")) : null;
  }
}
@@ -17,10 +17,10 @@
 0-20
-17
+20
  Jet
@@ -1069,24 +1069,105 @@
 ionType:%22);%0A
+%0A    if (exceptionTypes == null) %7B%0A      buf.append(%22 null%22);%0A    %7D%0A    else %7B%0A  
     for (Str
@@ -1203,32 +1203,34 @@
 nTypes) %7B%0A      
+  
 buf.append(%22 %22).
@@ -1253,25 +1253,34 @@
 _type);%0A    
-%7D
+  %7D%0A    %7D%0A
 %0A    buf.app

Fix NPE inside `ExceptionRangeCFG::toString()` for `finally` exception range