Imports System.Windows.Forms

Public Class Parser
  Implements Command
  Private stk As Stack
  Private actionList As ArrayList
  Private kdata As KidData
  Private dat As Data
  Private ptable As ListBox
  Private chn As Chain

  Public Sub New(ByVal line As String, _
      ByVal k As KidData, ByVal pt As ListBox)
    stk = New Stack()
    setData(k, pt)
    'Umieszczaj akcje w tablicy
    actionList = New ArrayList()
    buildStack(line)
    buildChain()                  'Utwórz łańcuch interpretera
  End Sub
  '----------------------------------------
  Private Sub buildStack(ByVal line As String)
    'Parsuj tokeny i utwórz stos
    Dim tok As StringTokenizer = New StringTokenizer(line)
    While (tok.hasMoreElements())
      Dim token As ParseObject = _
          tokenize(tok.nextToken())
      stk.push(token)
    End While
  End Sub
  '----------------------------------------
  Private Sub buildChain()
    chn = New VarVarParse()       'Początek łańcucha
    Dim vmvp As VarMultvarParse = New VarMultvarParse()
    chn.addToChain(vmvp)
    Dim mvvp As MultVarVarParse = New MultVarVarParse()
    vmvp.addtoChain(mvvp)
    Dim vrvp As VerbMultvarParse = New VerbMultvarParse()
    mvvp.addtoChain(vrvp)
    Dim vvp As VerbVarParse = New VerbVarParse()
    vrvp.addtoChain(vvp)
    Dim va As VerbAction = New VerbAction(actionList)
    vvp.addtoChain(va)
  End Sub
  '----------------------------------------
  Public Sub setData(ByVal k As KidData, ByVal pt As ListBox)
    dat = New Data(k.getData())
    ptable = pt
  End Sub
  '----------------------------------------
  'Analizuje i wykonuje polecenia
  Public Sub Execute() Implements Command.Execute
    Dim i As Integer
    While (stk.hasMoreElements())
      chn.sendToChain(stk)
    End While
    For i = 0 To actionList.Count - 1
      Dim v As Verb = CType(actionList(i), Verb)
      v.setData(dat, ptable)
      v.Execute()
    Next i
  End Sub
  '--------------------------------------
  Protected Function tokenize(ByVal s As String) As ParseObject
    Dim obj As ParseObject
    Dim typ As Integer
    Try
      obj = getVerb(s)
      typ = obj.get_Type          'Spowoduje wyjątek dla wartości null
    Catch e As NullReferenceException
      obj = getVar(s)
    End Try

    Return obj
  End Function
  '----------------------------------------
  Protected Function getVerb(ByVal s As String) As ParseVerb
    Dim v As ParseVerb
    v = New ParseVerb(s, dat, ptable)
    If (v.isLegal()) Then
      Return v.getVerb(s)
    Else
      Return Nothing
    End If
  End Function
  '----------------------------------------
  Protected Function getVar(ByVal s As String) As ParseVar
    Dim v As ParseVar
    v = New ParseVar(s)
    If (v.isLegal()) Then
      Return v
    End If
  End Function

End Class
