方案中的词法分析器

时间:2012-05-21 19:07:34

标签: scheme racket lexical-analysis

你好我们是非常新的编程方案,所以我试图在方案中构建一个词法分析器,基本上读取一个列表例如< SUM + 34 >,输出就像这样

{ is the left bracket 
SUM is an identifier
+ is the plus operator
34 is a Digit
} is the right bracket

我正在使用dr.scheme 而且程序并没有准确地告诉我我错过了什么或暗示我的错误。  对我来说一切都很新鲜

这是我到目前为止所尝试的:

(define alist'( < SUM + 34 >))

(define (token? object)
  (and (list? object)
       (not (null? object))
       (eq? (car object) 'token)))

(define (ident-token? token)
  (type-token? token 'IDENTIFIER))
(define (digit-token? token)
  (type-token? token 'DIGIT))
(define (op-token? token)
  type-token? token 'OPERATOR)

(define (type-token? token type)
  (and(type-token? token)
      (eq? (name-token token) type)))

(define (name-token token)
  (cadr token))

(define (value-token token)
  (caddr token))

(define (spot-token)
  (cadddr token))

(define (assign-token name value spot)
  (list 'token name value spot))

(define *peek* '())

(define (check-token alist)
  (let ((token (if (null? *peek*)
                   (<token> in)
                   *peek)))
    (set! *peek* '())
    token))

(define (peek-token alist)
  (let ((token (if (null? *peek*)
                   (read-token in)
                   *peek*)))
    (set! *peek* (if token token '()))
    token))

(define (<token> alist)
  (let* (next-loc (next-spot in)) (next-char (peek-char in))
    (cond ((eof-object? next-char) #f)
          ((char-whitespace? next-char)
           (begin (check-char in)
                  (<token> in)))
          ((char-ident-initial? next-char)
           (<identifier> (list (check-char in)) next-loc in))
          (else
           (let ((next-char (check-char in)))
             (cond ((char=? #\( next-char)
                    (assign-token 'LEFT-PAREN "(" next-loc))
                   ((char=? #\) next-char)
                    (assign-token 'RIGHT-PAREN ")" next-loc))
                   ((char=? #\` next-char)
                    (assign-token 'ADD-OP "+" next-loc))
                   ((char=? #\] next-char)
                    (assign-token 'SUB-OP "-" next-loc))
                   ((char=? #\{ next-char)
                    (assign-token 'MULT-OP "*" next-loc))
                   ((char=? #\} next-char)
                    (assign-token 'DIV-OP "/" next-loc))
                   (else
                    (syntax-error next-loc next-char))))))))

请伙计们,我正在尽力而为,我尝试编译。我用google搜索了很多东西,但我找不到可以帮助我的东西...... 即使你有教程或指南可以帮助我,请分享

1 个答案:

答案 0 :(得分:1)

我认为您在阅读错误消息时需要一些指导。

当我在DrRacket上面运行你的程序时,我收到错误:

expand: unbound identifier in module in: token

同时此功能中的token为红色:

(define (spot-token)  
  (cadddr token))     ; <---

这意味着编译器之前没有看到名称token

现在,由于您没有包含功能目的的描述, 我的猜测是,你忘了在参数列表中使用令牌:

(define (spot-token token)   
  (cadddr token))     

尽早发现错误很重要。 我的建议是每次你写一个新的函数,写在 在开始之前至少进行一到两次测试 下一个功能。