You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从字符串输入端口解析语法时行/列号被设为#f的原因

当从字符串输入端口解析语法时,行/列编号为何都被设为#f?

使用open-input-string创建字符串输入端口,再通过read-syntax解析语法对象时,调用syntax-line和syntax-column返回的都是#f,而非预期的行号和列号。

代码示例

(let* ([port (open-input-string "123")]
       [stx (read-syntax "my-input" port)])
  (printf "line ~a column ~a" (syntax-line stx) (syntax-column stx))
)

预期输出

line 1 column 0

实际输出

line #f column #f

原因解析

open-input-string创建的输入端口默认不启用行号/列号追踪功能,而read-syntax依赖端口的位置追踪数据来生成包含行、列信息的语法对象。如果端口没有开启位置追踪,语法对象自然无法获取到有效的行/列编号,只能返回#f。

解决方法

有两种方式可以开启端口的位置追踪:

  1. 在创建端口时指定起始行号
    open-input-string支持第三个参数(起始行号),传入该参数会自动启用位置追踪:

    (let* ([port (open-input-string "123" #f 1)] ; 第三个参数设为起始行号1
           [stx (read-syntax "my-input" port)])
      (printf "line ~a column ~a" (syntax-line stx) (syntax-column stx))
    )
    
  2. 调用port-count-lines!启用追踪
    对已创建的端口调用port-count-lines!,手动开启位置追踪:

    (let* ([port (open-input-string "123")])
      (port-count-lines! port) ; 启用行号追踪
      (let ([stx (read-syntax "my-input" port)])
        (printf "line ~a column ~a" (syntax-line stx) (syntax-column stx))
      )
    )
    

两种方法执行后,都会输出预期的line 1 column 0。


内容的提问来源于stack exchange,提问作者Martin Cejp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 06:36:16