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

72
LINES

< > BotCompany Repo | #1002839 // nlParse

JavaX fragment (include)

static new AtomicInteger nlParse_count; // how often did we parse something?

static Lisp nlParse(S s) {
  ret nlParse(s, true);
}

static Lisp nlParse(S s, boolean unbracket) {
  ret nlParse(codeTokens(snlTok(s)), unbracket, false, null);
}

static Lisp nlParse(S s, boolean unbracket, boolean explicitBrackets) {
  ret nlParse(codeTokens(snlTok(s)), unbracket, explicitBrackets, null);
}

static Lisp nlParse(L<S> tok) {
  ret nlParse(tok, true, false, null);
}

// unbracket refers to outermost brackets
// explicitBrackets refers to inner brackets
static Lisp nlParse(L<S> tok, boolean unbracket, final boolean explicitBrackets, L<S> warnings) {
  nlParse_count.incrementAndGet();
  
  class Entry {
    int i;
    Lisp tree;
    S wrapper;
    
    *(int *i) {
      tree = lisp("[]");
    }
    
    *(int *i, S bracket) {
      tree = lisp("[]");
      wrapper = bracket;
    }
    
    Lisp wrapped() {
      Lisp t = explicitBrackets ? tree : nlUnbracket(tree);
      ret wrapper == null ? t : lisp(wrapper, t);
    }
  }

  new L<Entry> stack;
  stack.add(new Entry(0));
  
  for (int i = 0; i < l(tok); i++) {
    S t = tok.get(i);
    if (eq(t, "[") || eq(t, "(")) {
      stack.add(new Entry(i, eq(t, "(") ? "()" : null));
    } else if (eq(t, "]") || eq(t, ")")) {
      if (l(stack) == 1)
        warn("too many closing brackets", warnings);
      else {
        Entry e = popLast(stack);
        /*if (!bracketsMatch(tok.get(e.i), t))
          warn("non-matching brackets");*/
        last(stack).tree.add(e.wrapped());
      }
    } else
      last(stack).tree.add(t);
  }
  
  while (l(stack) > 1) {
    warn("too many opening brackets", warnings);
    Entry e = popLast(stack);
    last(stack).tree.add(e.wrapped());
  }
  
  Lisp result = last(stack).wrapped();
  ret unbracket ? nlUnbracket(result) : result;
}

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1002839
Snippet name: nlParse
Eternal ID of this version: #1002839/1
Text MD5: 5f482de23f9ca0569efe9f8bd4866911
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2016-04-10 23:06:33
Source code size: 1905 bytes / 72 lines
Pitched / IR pitched: No / No
Views / Downloads: 741 / 911
Referenced in: #1006654 - Standard functions list 2 (LIVE, continuation of #761)
#3000382 - Answer for ferdie (>> t = 1, f = 0)
#3000383 - Answer for funkoverflow (>> t=1, f=0 okay)