Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

49
LINES

< > BotCompany Repo | #721 // "thread {" and "daemon {" (JavaX translator, v2)

JavaX translator [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (137L/2K/6K).

// Syntax: thread { doSomething(); }
// Short for: new Thread() { public void run() { doSomething(); }}.start();
// similar for daemon {}

!592 1000265 // auto-importer, standard function adder 

public class main {
  public static void main(String[] args) throws Exception {
    String s = loadMainJava();
    
    Pattern regex = Pattern.compile("(thread|daemon)\\s*\\{");
    
    for (int i = 0; i < 100; i++) {
      if (i == 99) System.out.println("Warning: 100 iterations!");
      Matcher matcher = regex.matcher(s);
      if (!matcher.find())
        break;

      int start = matcher.start(), end = matcher.end();
      int endOfBlock = findEndOfBlock(s, end);
      boolean daemon = matcher.group().startsWith("d");
      
      String var = "_t_" + i;
      String code = "Thread " + var + " = new Thread() {\n" +
        "public void run() {\n" +
        "try {\n" +
        s.substring(end, endOfBlock) + "} catch (Exception _e) {\n" +
          "  throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }\n};\n" +
        (daemon ? var + ".setDaemon(true);\n" : "") +
        var + ".start();";
      s = s.substring(0, start) + code + s.substring(endOfBlock+1);
    }
    
    saveMainJava(s);
  }
  
  // start is the index AFTER the opening bracket
  // returns index OF closing bracket
  static int findEndOfBlock(String s, int start) {
    int level = 1;
    for (int i = start; i < s.length(); i++) {
      if (s.charAt(i) == '{') ++level;
      else if (s.charAt(i) == '}') --level;
      if (level == 0)
        return i;
    }
    return s.length();
  }
}

Author comment

Began life as a copy of #673

download  show line numbers  debug dex  old transpilations   

Travelled to 22 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, ddnzoavkxhuk, dhtvkmknsjym, gwrvuhgaqvyk, ishqpsrjomds, jlatgrcjtklg, jtubtzbbkimh, kmhbujppghqa, liwcxgsjrgqn, lpdgvwnxivlt, mqqgnosmbjvj, mrjhfnjfopze, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, teubizvjbppd, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #721
Snippet name: "thread {" and "daemon {" (JavaX translator, v2)
Eternal ID of this version: #721/1
Text MD5: e682691166e3126473c50e01d9f2bb74
Transpilation MD5: d9bc21e24b8d67fc91260897a61a1dff
Author: stefan
Category:
Type: JavaX translator
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2016-01-22 00:01:22
Source code size: 1663 bytes / 49 lines
Pitched / IR pitched: No / No
Views / Downloads: 712 / 16461
Referenced in: [show references]