rules for transforming casts to declarations?

Steve Vegdahl stevev at tekchips.LABS.TEK.COM
Wed Mar 15 05:38:12 AEST 1989


I am working on a preprocessor that needs to---among other things---transform
between "cast-style" types and "declaration-style" types.  For example,
the user's input might contain the string:
  (int (*)())
The preprocessor would need to tranform this into the declaration:
  int (*foo)();

I am treating this problem as a transformation from a list of tokens to
a list of tokens.  (We can assume that the original list is a well-formed
cast expression.)

Not being an expert on C type-declarations, I would appreciate opinions as
to whether this method handles all cases and, if not, some examples
cast-expressions on which it will fail.

Thanks.
		Steve Vegdahl
		Computer Research Lab
		Tektronix Labs
		Beaverton, Oregon

----------------------------------------------------------------

Alleged algorithm for transforming cast-style type into a declaration.

  1. strip away the outer parentheses of the cast expression
  2. find the position to insert the to-be-declared identifier
      a. skip over all identifiers, left parentheses, and asterisks (i.e.,
         go until you hit a right parenthesis, left bracket or end of string)
      b. if the token that "stopped us" was a right parentheses, and the
         previous tokens a left parentheses, back up on
  3. insert the identifer in the current position
  4. add a semicolon to the end

Example #1: declare "foo" as a "(float *)":
  after step 1: "float *"
  after step 2: "float * "
			^current position
  after step 3: "float * foo"
  after step 4: "float * foo;"

Example #2: declare "foo" as an "(unsigned float **[]())"
  after step 1: "unsigned float **[]()"
  after step 2: "unsigned float ** []()"
				  ^current position
  after step 3: "unsigned float ** foo []()"
  after step 4: "unsigned float ** foo []();"

Example #3: declare "foo" as an "(int (*)())"
  after step 1: "int (*)()"
  after step 2: "int (* )()"
		       ^current position
  after step 3: "int (*foo)()"
  after step 4: "int (*foo)();"

(Is the algorithm for going the other direction simply that of removing the
declared name and the semicolon and surrounding the entire thing with
parentheses?)



More information about the Comp.lang.c mailing list