我在frama-c中开发了一个插件,我想在源代码中获取行号。在这个小脚本中,例如:
open Cil_types
open Cil_types
open Cil_datatype
let print_loc kf =
let locals = Kernel_function.get_locals kf in
List.iter (fun vi ->
let line = Cil_datatype.Location.pretty_line Format.sprintf "%a" Printer.pp_location vi.vdecl in
Format.printf "Line %a: %a %s@."
Printer.pp_location vi.vdecl Printer.pp_typ vi.vtype vi.vname
) locals
let () =
Db.Main.extend (fun () ->
Format.printf "Printing all local vars...@.";
let fun_name = "main" in
let kf = Globals.Functions.find_by_name fun_name in
print_loc kf;
Format.printf "done!@.")
Printer.pp_location
打印完整路径。我只想要行号。
我在pretty_line
模块中找到Cil_datatype.Location
并尝试使用它,但我不能。我收到编译错误,但我没有找到在Frama-C源中使用此函数的示例。
我试过了,
let print_loc kf =
let locals = Kernel_function.get_locals kf in
List.iter (fun vi ->
let line = Cil_datatype.Location.pretty_line Format.sprintf "%a" Printer.pp_location vi.vdecl in
Format.printf "Line %d: %a %s@." line Printer.pp_typ vi.vtype vi.vname) locals
我收到此错误消息
错误:此函数具有类型 Format.formatter - > Cil_datatype.Location.t - >单元 它适用于太多的论点;也许你忘记了一个`;'。
我尝试了几种组合,但无论如何,要么我收到上一条错误消息,要么收到此消息:
错误:此表达式具有类型 Format.formatter - > Cil_types.location - >单元 但是预期表达式为单位 - > ' a - >串 类型Format.formatter与类型单元
不兼容
我可以获得有关行号的信息吗?或者我如何正确使用Cil_datatype.Location.pretty_line
?
由于
答案 0 :(得分:4)
octachtron的回答很好地总结了如何将pretty_line
与格式字符串一起使用。但是,如果要将行号用作整数(不一定要使用%d
打印),Cil_datatype.Location.t
是一种具体类型,更准确地说是Cil_types.location
的别名,这是本身是一对Lexing.location
。因此,
要检索位置开始的行,您只需执行
...
let line = (fst vi.vdecl).Lexing.pos_lnum in
...
答案 1 :(得分:3)
Format.formatter -> 'a -> unit
类型的函数旨在与%a
说明符结合使用,例如格式化程序ppf
和位置loc
:
let () = Format.fprintf ppf "%a" Cil_datatype.Location.pretty_line loc
一个特殊情况是,如果你想生成一个字符串,你应该使用asprintf
而不是sprintf
:
let s = Format.asprintf "%a" Cil_datatype.Location.pretty_line loc