CP2 - Parser

Get input character stream from tokenizer, then build the parse tree. (PT)

  • Parent node to create an “empty” child node

  • Pass the row number corresponding to the newly created node as argument

  • Example: ParseIf() --
    • Call getToken(), check it is an 'if'
      • If not, print error and stop
  • Example: ParseStmt() --
    • Call getToken, return a number, and apply one-token look ahead
    • Call corresponding alternative, e.g. ParseIf()
      • If the getToken returns an identifier, call parseAssign();
  • Example: ParseExp() -- "9-5+4"
  1. Check if current node is a <fac>
  2. PT[n,0] = type_fac
  3. PT[n,2] = nextRow++; // next free row in PT[]
  4. Call ParseFac(PT[n,2]), create 1st child node
  5. Call getToken() and check its type
    1. if it is a '+' -- PT[n,1] = 2
    2. if it is a '-' -- PT[n,1] = 3
    3. Otherwise -- PT[n,1] = 1, return
  6. if PT[n,1] is 2/3, skipToken()
  7. PT[n,3] = nextRow++; // next free row in PT[]
  8. Call ParseExp(PT[n,3])
  9. return;
  • Example: ParseFac()
  1. Check if current node is an <op>
  2. PT[n,0] = type_op
  3. Call ParseOp()
  4. Call getToken()
    1. if the returned value is a '*',  -- PT[n,1] = 2, skipToken()
    2. if the returned value is not a '*',  -- PT[n,1] = 1, return
  5. Call parseFac() if it is the 2nd alternative, then return
  • ParseAssign() -- 
    • Check if the node is an identifier
      
      PT[n,0] = 7; // this is an <assign> node, construct the row and skip that token (for now)
      
    • PT[n,2] = nextRow++; // next free row in PT[]
      
    • Call ParseID(PT[n,2]) -- the identifier to the left of the '='
    • Now curser at '=', and check if it is actually a '=', then skipToken()
    • PT[n,3] = nextRow++; // next free row in PT[]
      
    • Now parse the expression on the right of the '=' -- parseExp()
    • if (s != ‘‘;’’} {**Quit!!**} else {T.skipToken();};
      return; }
      

        ParseID()

  • Call getToken() and check if it is an ID
  • Call IdName of the identifier
  • Check the global variable to know if we are parsing <decl seq> or <stmt seq>
  • Get the string, and look up that string in the IdName table to see if it is there, and make decision based on that 
  • ParseID() construct the ID node and the put the id in the IdName table
  • Skip pass the identifier -- skipToken()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值