2015-05-15 28 views
1

我是新来的球拍,但超级兴奋。我一直在为WWW-Authenticate头文件编写一个简单的词法分析器。我对轻松愉快感觉不错,但现在我想改变我的输出。球拍词汇表 - 退货清单的缺点

#lang racket 

(require parser-tools/lex) 
(require (prefix-in : parser-tools/lex-sre)) 

(define in (open-input-string "MsRtcOAuth href=\"https://foo.com/WebTicket/oauthtoken\",grant_type=\"urn:microsoft.rtc:windows,urn:microsoft.rtc:anonmeeting,password\", Bearer trusted_issuers=\"\", client_id=\"00000004-0000-0ff1-ce00-000000000000\"")) 


(define key-lexer 
    (lexer 

    ;anything not an "=" 
    [(:* (char-complement #\=)) 
    ;=> 
    (cons `(KEY, lexeme) 
     (equals-lexer input-port))] 

    ;eof 
    [(eof) '()])) 

(define equals-lexer 
    (lexer 
    [#\= 
    ;=> 
    (value-lexer input-port)] 

    ;eof 
    [(eof) '()])) 

(define value-lexer 
    (lexer 
    ;values are anything between two " " 
    [(concatenation #\" (:* (char-complement #\")) #\") 
    ;=> 
    (cons `(VAL, lexeme) 
      (comma-lexer input-port))] 

    ;eof 
    [(eof) '()])) 

(define comma-lexer 
    (lexer 
    [(concatenation (:* whitespace) #\, (:* whitespace)) 
    ;=> 
    (key-lexer input-port)] 

    ;eof 
    [(eof) '()])) 

(key-lexer in) 

眼下,输出看起来是这样的:

'((KEY "MsRtcOAuth href") 
(VAL "\"https://foo.com/WebTicket/oauthtoken\"") 
(KEY "grant_type") 
(VAL "\"urn:microsoft.rtc:windows,urn:microsoft.rtc:anonmeeting,password\"") 
(KEY "Bearer trusted_issuers") 
(VAL "\"\"") 
(KEY "client_id") 
(VAL "\"00000004-0000-0ff1-ce00-000000000000\"")) 

什么我宁愿是对的列表,与此类似:

(("MsRtcOAuth href" . "\"https://foo.com/WebTicket/oauthtoken\"") 
("grant_type" . "\"urn:microsoft.rtc:windows,urn:microsoft.rtc:anonmeeting,password\"") etc... 

任何帮助或指针大大赞赏。谢谢!

回答

1

这里是把你有什么到你想要的东西的一种方式:

(define (prettify key-val-pairs) 
    (match key-val-pairs 
    [(list (list 'KEY key) (list 'VAL val) more ...) 
    (cons (list key val) 
      (prettify more))] 
    [_ key-val-pairs])) 


(prettify 
'((KEY "MsRtcOAuth href") 
    (VAL "\"https://foo.com/WebTicket/oauthtoken\"") 
    (KEY "grant_type") 
    (VAL "\"urn:microsoft.rtc:windows,urn:microsoft.rtc:anonmeeting,password\"") 
    (KEY "Bearer trusted_issuers") 
    (VAL "\"\"") 
    (KEY "client_id") 
    (VAL "\"00000004-0000-0ff1-ce00-000000000000\""))) 

输出:

'(("MsRtcOAuth href" "\"https://foo.com/WebTicket/oauthtoken\"") 
    ("grant_type" "\"urn:microsoft.rtc:windows,urn:microsoft.rtc:anonmeeting,password\"") 
    ("Bearer trusted_issuers" "\"\"") 
    ("client_id" "\"00000004-0000-0ff1-ce00-000000000000\"")) 
+0

这真是太好了。在Lexing功能中有没有办法做到这一点?我应该使用解析库吗? –

+0

词法分析器按照令牌出现的顺序产生值。任何重新排序通常在解析器中完成。 – soegaard

+0

在这种情况下,不需要使用解析库。函数prettify是解析器。 – soegaard