Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Design

Letters


JAN89: LETTERS

Find that Function (Again)

Dear DDJ,

The article "Find that Function" caught my attention. I imagine every programmer, at some time, wants a list of functions or other declarations, particularly for a sizable program distributed over many source files.

I was surprised by the complexity of the code used to build the function list in Hymowech's Listing One (pages 70-74), perhaps 400 lines of code and comments. Surely there should a simpler way of doing this. The problem is how to extract all instances of a particular grammar element, the identifier of a function definition, from a source file presented as a character stream. This is made difficult by the start of the definition (function type, name, parameter declarations, and beginning of the function body) being commonly on more than one line, having a varied arrangement of white space and punctuation, comprising many different tokens, and possibly including comment lines.

Lex, a generator of automatons for lexical analysis, is admirably suited for this particular kind of pattern-matching problem. My example code gives Lex sources for two filters and a wrapping shell script. The definitions (FUNCSTRT, etc.) were written in the hope that they make self-explanatory the few pattern-action rules given at the end of each source, following the %% symbol. Mk_funclist.one and its dependents serve to build a table of functions from a list of C source files.

The seven rules in the two Lex sources duplicate, I believe, the essential actions of Listing One of "Find that Function." The design of Listing One assumes that preprocessor directives within the function body do not alter the curly brace balance. If this is not true, my second example shows that the preprocessor itself can be used to sort things out. A few changes in Listing One serve to change it into a generator of a list of all declarations, each on one line, with parameter declarations and return value given on the line for each function (a lint library).

There are tremendously powerful tools for pattern matching and extraction of elements from text files. Public domain versions of Lex that run on non-Unix systems have been available for some time. awk is sold for non-Unix systems (should I say MS-DOS?). They run on simple hardware; the Lex sources of Examples 1 and 2 were worked out on a PC AT. The problem is choosing the best tool. For problems like the one addressed here, Lex is arguably the most appropriate. Lex processes character streams simply, with new lines having no special meaning, and so it differs from line-oriented tools, like sed and awk. Lex also tests left and right context simply. Consider the last rule of Listing One. It prints the NAME when the right context matches FUNCSTRT and when the left-context flag NORM ensures that NAME is not inside a function body. The same parsing likely could be accomplished also by use of awk or sed, but the code for these tools would be more complicated. My intent is not to push Lex as an all-purpose solution for text manipulation. The filters of Listing Two, unlike those of Listing One, could just as easily have been written for awk or sed.

Example 1

  # MK_FUNCLIST.ONE
  echo "                   /*****FUNCTION LIST*****/\n"
  for i; do
          echo "\n/* 'basename ${i} '*/"
          cat ${i}|uncomment |funcfilt 3
  done

  % {
  /*UNCOMMENT- based on usenet posting by: */
  /*      Chris Thewalt; [email protected] */
  %}
  STRING         \"([^"\n]|\\\")*\"
  COMMENT        "/*"([^*\n]|"*"+[^*/\n])*"*"*"*/"
  %%
  {COMMENT}                            ;
  {STRING}                             ECHO;
  .|\n                                 ECHO;

  %{
  /*-FUNCFILT3: print function names, indented 1 tab; */
  /*DECL & FUNCPTR may require change for ANSI compatibility */
  %}
  int curly;
  WLF             ([ \t\n\f\r]*)
  NAME            ([*]*[_a-zA-Z] [_a-zA-ZO-9]*)
  ARRAY           (\[[0-9+-/*]*\])
  DECL            ([;,]|{WLF}|{NAME}|{ARRAY})
  FUNCPTR         (\({DECL}*\)\({DECL}*\))
  DECLST          ({DECL}|{FUNCPTR})*
  FUNCSTRT        ([ \t]*\({DECLST}\){DECLST}\{)
  STRING          \"([^"\n]|\\\")*\"
  SKIPALLQUOTED   ({STRING}|\'.\'|\\.)
  %START CURLY NORM
  % {
  main()  {
          /* if no shell wrapper, loop over files here */
          /* and run other filters using tmp files */
          BEGIN NORM;
          yylex();
  }
  %}
  %%
  <CURLY>\{               curly++;
  <CURLY>\}               {if (--curly == 0) {BEGIN 0; BEGIN NORM;}}
  {SKIPALLQUOTED}|.|\n            ;
  <NORM> {NAME}/{FUNCSTRT}        (printf ("\t%s\n", yytext);
           curly=0;BEGIN 0;BEGIN CURLY;}

Example 2

  # MK_FUNCLIST.TWO
  echo"                   /*****FUNCTION LIST*****/\n"
  for i; do
          echo "\n/*'basename ${i}'*/"
          cat $ {i}| funcfilt1|/lib/cpp -P -Cl
                   funcfilt2|uncomment|funcfilt3
  done

  %{
  /*-FUNCFILT1: prepare for cpp execution of #ifdefs, etc.; */
  /*i.e., setup to restore #includes & remove code added by cpp */
  %}
  %%
  ^\#[ \t]*include.*$            {printf("/*%s*/\n", yytext);
          printf ("/*DINGDONGDELL*/\n");
          printf ("%s\n", yytext);
          printf ("/*DELLDONGDING*/\n:);}
  .|\n                              ECHO;

  %{
  /*-FUNCFILT2: remove cpp-included code, restore #include's */
  %}
  %START DING
  %%
  ^"/*DINGDONGDELL*/"$               BEGIN DING;
  ^"/*DELLDONGDING*/"$               BEGIN O;

  <DING>^"/*#"[^*]*"*/"$             ;
  <DING>.|\n                         ;
  ^"/*#"[^*]*"*/"$                   {yytext [yyleng-2] = 0;
           printf ("%s",  &yytext[2]);}
  ^[\t]*\n                           ;
  .|\n                               ECHO;

With Lex, awk, and other such armament in hand, there would seem to be little justification for coding the solution to a text manipulation problem from scratch. Programmers should be encouraged to use the excellent tools available and should have the knowledge to choose the one right for the job. I hesitate to suggest that Dr. Dobb's should take its readers through discussions of the internals or give tutorials on the use of "mature" tools like Lex, yacc, and awk. You could, however, take care to give readers programming examples that, rather than showing the long and wrong way to solve a problem, show them the appropriate use of tools.

John Rupley

University of Arizona

Tucson, Arizona

Ada Aid

Dear DDJ,

I've read with interest the Ada articles in the September 1988 issue and hope to see more such features in the future.

In "Object-Oriented Dimensional Units," John Grosberg presents a useful example of how a dimensioned unit with a float-type value might be implemented as a reusable component in Ada. However, I think one of his main points is misleading.

In discussing the operations that the dimensional unit type Float_Unit.Class inherits from the predefined type Float, Mr. Grosberg notes that some operations are invalid. For example, 5 feet x 4 feet = 20 square feet, not 20 feet. He then states the "Ada provides no way to detect it (an invalid operation) at compile time" and presents a way to detect the error at run time.

One way to detect such an invalid operation at compile time is to implement the type "Class" as a private type. Objects of a private type may be manipulated only by the operations provided in the visible part of the spec. If invalid operations are not explicitly provided, then they are not available to a client. The integrity of the abstraction is thereby preserved, and invalid operation attempts are discovered at compile time.

Use of private (and limited private) types is even more important when a class is implemented as an array or record, which is often the case. Typically, individual components of a composite type need to be protected from manipulation by the clients. This is accomplished by use of private types which provide a more accurate abstraction, a cleaner interface for the client, more precise control of operations on the class, and minimization of side effects of any changes to the internal representation of the type.

The code on page 12 shows the revisions to Mr. Grosberg's Float_Unit spec required to make type "Class" a private type. "Class" is declared as type private instead of type Float. The private part is inserted at the end of the spec, and "Class" declaration is completed in the private part. The invalid function declarations are then removed from the spec. The Units_Error exception declaration is also removed.

In the Float_Unit body, only the removal of the invalid function bodies is required. Package Float_Unit is shown in Listing One.

Glenn A. Edwards

St. Petersburg, Fla.

John responds: My statement that "Ada provides no way..." sounds more absolute than I intended. I would have been more correct had I said "having chosen to make float_unit.class public, Ada provides no way...." Any method of doing something has advantages and disadvantages relative to the application. One most choose the method that best fits the circumstances. Mr. Edwards' method for making float_unit.class into a private type is the way I started the design of the float_unit package. For my application, however, I eventually chose to make the type public for two main reasons: First, I wanted to be able to use floating point literals with variables of the various units types. For example, I wanted to be able to say:

supply_voltage : volt.class := 5.2;   
or       supply_voltage := 10.0;

Second, I wanted to be able to use the range declaration and checking features that are available for floating point types in Ada. So, for example, I could do something like this.

supply_voltage: volt.class range 0.0
                    .. 10.5;

I think it is safe to say neither of these capabilities is available if the type is private. One could (if the type were private) obtain the effect of my first example by adding a function to the package to convert floating point to float_unit.class:

function to_class( f : float ) return
                    class;

and use it as an inherited function like this:

supply_voltage : volt.class :=
               volt.to_class(5.2);

But that seems less natural, and, besides, the range feature that I wanted still wouldn't be available. In addition, there is little reason to hide the fact that a dimensional unit is based on float, since that is the way we think about them anyway. It is only necessary to "hide" or restrict the ways they can be combined with each other. What I traded for the features I wanted was to postpone the checking of some invalid operations to run-time. By the way, if Mr. Edwards or any other readers are interested in an altogether different method of handling units in Ada, I recommend they check out the article "Dimensional Analysis in Ada" by Pat Rogers, published in the ACM Ada Letters, vol. 8, no. 5, Sept./Oct. 1988.

Leftie Light Bulbs

Dear DDJ,

I enjoyed reading Steve Upstill's article on RenderMan Shading Language("Photorealism in Computer Graphics," November 1988, but Figures 1 and 3 provided compelling examples of why software people have to be watched so closely out in the real world. The threads on the light bulbs are left-handed. And another thing: Threads are helixes, not spirals.

Fred Klingener

McLean, Virginia

Editor's note: Unfortunately, the slide was flopped during the printing process. The error was not the programmer's.

Algorithmic Answer for Alan

Dear DDJ,

Software Manual for Elementary Functions (by William J. Cody Jr. and William Waite, Prentice-Hall) should help Alan Clark, who needs a resource that lists fundamental algorithms for high-level functions that do not exist in machine code. (See "Letters," August 1988.) The book gives detailed implementation of sqrt, alog, alog10, exp, power, sin, cos, tan, cot, asin, acos, atan, atan2, sinh, cosh, tanh, and provides a test suite to boot.

Edmund Ramm

Kaltenkirchen, W. Germany


Copyright © 1989, Dr. Dobb's Journal


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.