Skip to content
Tcl Source Code Ticket Change Details
Login

Ticket Change Details

Overview

Artifact ID: bd56dcce5fca5f6bbf760eb72aa8f0c673833093a90aa806569b7e8254da896e
Ticket: 008773b7a3cdd530a184b2e8902d0679e246de74
how to log Tcl commands that are executed via the source command using the Tcl C API
User & Date: sebres on 2025-07-24 10:29:12
Changes

  1. closedate changed to: "2460880.93694851"
  2. closer changed to: "sebres"
  3. icomment:
    At top level in source, you can use `[info script]` or at C-level `((Interp*)interp)->scriptFile`.
    
    Everywhere in script (not at top level only, but also in proc or namespace), you can get a dict with the file and line with `[info frame 0]` or at C-level `TclInfoFrame` (internal only).
    
    You can try this to see how it works:
    
    ```
      puts [info script]
      puts [info frame 0]
      proc test {} {
        puts [info frame 0]
      }
      test
      namespace eval test {
        puts [info frame 0]
      }
      eval [concat apply {{{} {puts [info frame 0]; puts [info frame 1]}}}]
      {*}[list if 1 {puts [info frame 0]; puts [info frame 1]}]
      after 0 {puts [info frame 0]; puts [info frame 1]}
      update
    ```
    
    Calling from C-level of command, you can obtain the frame info either with TclInfoFrame (if you have Tcls internals and it is a bit complex, see Tcls source code),<br/>
    or using `objProc()` of Command `::tcl::info::frame` called with int-object 0, 1, or whatever level you need.
    
    Or with something like this:
    
    ```
      if (Tcl_Eval(interp, "info frame 1") != TCL_OK) return TCL_ERROR;
      Tcl_Obj *res = Tcl_GetObjResult(interp);
    ```
    And then use `Tcl_DictObjGet` to obtain `file` and `line` from result dict.<br/>
    Note that it uses 1 as level to obtain frame from parent (caller), because Tcl_Eval would also insert a frame during its execution.
    
    Also note that this frame info may not contain the source file and line information, if the command is invoked not directly from source, but asynchronously as events or from code dynamically built and evaluated hereafter (see last 3 examples above), so you may need to traverse over upper levels (e. g. `info frame 2` etc) till you'd find the caller frame containing the info.
    However there are cases where obtaining of origin may be impossible at all, because not every "evaluable" tcl-object contains line information with its origin (since the Tcl is JIT compiler, and TEBC compilation, NRE trampoline, etc may make it too difficult or almost impossible for certain constellations).
    
  4. login: "sebres"
  5. mimetype: "text/x-markdown"
  6. status changed to: "Closed"