TIP #265 Version 1.7: A Convenient C-side Command Option Parser for Tcl

This is not necessarily the current version of this TIP.


TIP:265
Title:A Convenient C-side Command Option Parser for Tcl
Version:$Revision: 1.7 $
Author:Sam Bromley <sam at sambromley dot com>
State:Final
Type:Project
Tcl-Version:8.6
Vote:Done
Created:Monday, 03 April 2006
Keywords:Command line parsing, C implementation

Abstract

The Tk C library provides developers with a Tk_ParseArgv() function that allows command line parsing of options of the "-option" form. Archived discussions on news:comp.lang.tcl and on the Wiki indicate that a desire for similar functionality without Tk has arisen several times in the past. This TIP presents a Tk-free implementation of Tk_ParseArgv() named Tcl_ParseArgvObj, that developers can use to parse "-option" style command options in C implementations of Tcl commands using the Tcl_Obj interface.

Rationale

While the parsing of command options can be readily accomplished on the Tcl side, a uniform method for parsing "-option" formed options does not exist on the C side. Many developers are familiar with the ease of use of libpopt-style command line parsing, but a similarly clean method does not currently exist in Tcl. The common approach is to use Tcl_GetIndexFromObj(), yet this method alone does not allow the flexibilty and ease of use of libpopt-style parsing.

One drawback of the classical Tcl_GetIndexFromObj()-only approach is the need to handle the specifies of your command option parsing for each unique command. This leads to significant code duplication. A libpopt-style approach is to bundle all of your parsing specifics into a single array of structures capturing the details, and then let a specific parsing routine handle the parsing of every option for you. The Tcl_ParseArgvObj() routine introduced in this TIP provides this functionality, thereby allowing the removal of all parsing specifics from the command implimentation other than that necessary to describe each optional argument.

Additionally, a function Tcl_ParseArgsObjv is provided to provide the functionality of Tk_ParseArgs() to those who desire it. A discussion in 2002 on news:comp.lang.tcl [