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

54
LINES

< > BotCompany Repo | #1003920 // Test Bracket Hygiene

JavaX source code [tags: use-pretranspiled] - run with: x30.jar

Libraryless. Click here for Pure Java version (947L/7K/23K).

1  
!752
2  
3  
p {
4  
  test("{[(a)]}", true); // ok
5  
  test("[(a)"); // not closed
6  
  test("a)"); // not opened
7  
  test("(a)}"); // not opened
8  
  test("(a]"); // mismatch
9  
  print("\nALL TESTS OK");
10  
}
11  
12  
static void test(S s) {
13  
  test(s, false);
14  
}
15  
16  
static void test(S s, bool ok) {
17  
  assertEquals(s, ok, testImpl(s));
18  
  print("ok");
19  
}
20  
21  
static bool testImpl(S s) {
22  
  print();
23  
  print(s);
24  
  
25  
  // not <> as they are ambiguous (< is also a comparison operator)
26  
  S op = "([{", close = ")]}";
27  
  
28  
  L<S> tok = javaTok(s);
29  
  new Map<Int, Int> map;
30  
  L<int> stack = getBracketMap2(tok, map, op, close);
31  
  if (nempty(stack)) {
32  
    print("Bad hygiene - " + n(l(stack), "bracket") + " not closed");
33  
    false;
34  
  }
35  
  
36  
  if (map.containsKey(0)) {
37  
    print("Bad hygiene - bracket not opened (" + quote(tok.get(map.get(0))) + ")");
38  
    false;
39  
  }
40  
  
41  
  for (int i : keys(map)) {
42  
    int j = map.get(i);
43  
    S a = tok.get(i), b = tok.get(j);
44  
    //print("i=" + i + ", j= " + j + ", a=" + quote(a) + ", b=" + quote(b));
45  
    int ai = op.indexOf(a), bi = close.indexOf(b);
46  
    if (ai != bi) {
47  
      print("Bad hygiene - brackets don't match (" + quote(a) + " vs " + quote(b) + ")");
48  
      false;
49  
    }
50  
  }
51  
  
52  
  print("Hygiene OK!");
53  
  true;
54  
}

download  show line numbers  debug dex  old transpilations   

Travelled to 15 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, ddnzoavkxhuk, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1003920
Snippet name: Test Bracket Hygiene
Eternal ID of this version: #1003920/1
Text MD5: f582b731637739a471f757b33bc5344d
Transpilation MD5: bc5b676a9adb56399b2e164a12108c21
Author: stefan
Category: javax
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2016-07-30 18:30:17
Source code size: 1259 bytes / 54 lines
Pitched / IR pitched: No / No
Views / Downloads: 517 / 571
Referenced in: [show references]