// HC016: Unused Using/Alias
// Detects `using ... as Alias` where Alias is never referenced as `Alias.` in the source.
static box RuleUnusedAliasBox {
  apply(text, path, out) {
    if text == null { return 0 }
    local lines = me._split_lines(text)
    local i = 0
    while i < lines.size() {
      local ln = me._ltrim(lines.get(i))
      if ln.indexOf("using ") == 0 && ln.indexOf(" as ") > 0 {
        // parse alias name after ' as '
        local p = ln.indexOf(" as ")
        local rest = ln.substring(p + " as ".length())
        local alias = me._read_ident(rest)
        if alias != "" {
          // search usage: alias.
          local needle = alias + "."
          if text.indexOf(needle) < 0 {
            out.push("[HC016] unused alias '" + alias + "' in using: " + path + ":" + me._itoa(i+1))
          }
        }
      }
      i = i + 1
    }
    return 0
  }
  _split_lines(s) { local arr=new ArrayBox(); if s==null {return arr} local n=s.length(); local last=0; local i=0; loop(i<n){ local ch=s.substring(i,i+1); if ch=="\n" { arr.push(s.substring(last,i)); last=i+1 } i=i+1 } if last<=n { arr.push(s.substring(last)) } return arr }
  _ltrim(s) { return me._ltrim_chars(s, " \t") }
  _ltrim_chars(s, cs) { local n=s.length(); local head=0; local idx=0; while idx<n { local ch=s.substring(idx,idx+1); if ch!=" " && ch!="\t" { head=idx; break } if idx==n-1 { head=n } idx=idx+1 } return s.substring(head) }
  _itoa(n) { local v=0+n; if v==0 { return "0" } local out=""; local digits="0123456789"; local tmp=""; while v>0 { local d=v%10; tmp=digits.substring(d,d+1)+tmp; v=v/10 } out=tmp; return out }
  _is_ident_char(c) { if c=="_" {return 1}; if c>="A"&&c<="Z" {return 1}; if c>="a"&&c<="z" {return 1}; if c>="0"&&c<="9" {return 1}; return 0 }
  _read_ident(s) { if s==null {return ""} local n=s.length(); local i=0; local out=""; while i<n { local ch=s.substring(i,i+1); if me._is_ident_char(ch)==1 { out=out+ch; i=i+1; continue } break } return out }
}

static box RuleUnusedAliasMain { method main(args) { return 0 } }

