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

C/C++

A Frame-Based Message-Passing Parser for C


Listing Four shows the parser that determines if a statement is a C function declaration. The function needs only to return TRUE or FALSE depending on the syntax of its input.

Listing Four

int is_c_function_declaration (char *start_ptr) {

  int i;
  int returnval = TRUE;
  int openparen = FALSE;
  int lasttoken = ERROR,
    lasttoken_2 = ERROR, 
    lasttoken_3 = ERROR;
  int lasttoken_ptr;    
  char *buf;
  char *open_block_ptr; 

  if ((open_block_ptr = index (start_ptr, '{')) == NULL)
    return FALSE;

  if ((buf = (char *) calloc (open_block_ptr - start_ptr + 2, 
			      sizeof (char))) == NULL)
    error ("Is_c_function_declaration: %s", strerror (errno));


  strncpy (buf, start_ptr, open_block_ptr - start_ptr + 1);
  buf[open_block_ptr - start_ptr + 1] = 0;

  tokenize (buf);

  if (c_messages[c_message_ptr + 1] -> tokentype != OPENBLOCK)
    parser_error 
      ("Is_c_function_declaration: Function start not found.");

  for (i = N_MESSAGES; i > c_message_ptr; i--) {

    if ((c_messages[i] -> tokentype == WHITESPACE) ||
	(c_messages[i] -> tokentype == NEWLINE))
      continue;

    switch ( c_messages[i] -> tokentype )
      {
      case LABEL:
	if (!strcmp (c_messages[i] -> name, "main"))
	  main_declaration = TRUE;
	break;
      case OPENPAREN:
	if ((c_messages[lasttoken_ptr] -> tokentype != LABEL) ||
	    is_c_keyword (c_messages[lasttoken_ptr]->name))
	  returnval = FALSE;
	if ((lasttoken_2 != LABEL) && (lasttoken_2 != CHAR))
	  returnval = FALSE;
	/* Check for a method declaration. */
	if ((lasttoken_3 == LABEL) && (lasttoken_2 == LABEL) && 
	    (lasttoken == LABEL))
	  returnval = FALSE;
	openparen = TRUE;
	break;
      case CLOSEPAREN:
	if (!openparen)
	  returnval = FALSE;
	break;
      case SEMICOLON:
	returnval = FALSE;
	goto done;
	break;
      case OPENBLOCK:
	if (c_messages[lasttoken_ptr] -> tokentype != CLOSEPAREN)
	  returnval = FALSE;
	break;
      case CLOSEBLOCK:
	returnval = FALSE;
      default:
	break;
      }

    lasttoken_ptr = i;
    lasttoken_3 = lasttoken_2;
    lasttoken_2 = lasttoken;
    lasttoken = c_messages[i] -> tokentype;
  }

 done:
  delete_c_messages ();
  free (buf);

  return returnval;
  
}

Is_c_function_declaration() can syntactically match declarations of the following types, as well as others. In addition, the function can distinguish between C function declarations and ctalk method declarations without performing semantic analysis; for example, by checking for ctalk's, "method," method or looking up object references:

int main (int argc, char **argv) {
}

char *newstring (void) {
}

FILE *openfile (char *path) {
}

Most of the functions that distinguish C language statements, such as function and variable declarations, are able to use the messages of the already tokenized input. Is_c_function_declaration(), however, must perform its own tokenization because it helps determine the placement of stack frames during the first pass of the parser.

It is worth noting that is_c_function_declaration() checks for the main() function declaration. This allows the interpreter to place the ctalk initialization code in the output file at the end of the preamble, immediately before main(), and to call the initialization code as the first statement in main() after the variable declaration statements. GCC, at least, requires that variable declarations occur at the beginning of a program block, before any statements.

The preprocessor statement parser is slightly more complex than is_c_function_declaration() because it must analyze #ifdef... #else... #endif clauses, as well as parenthetical subexpressions and #define and #undef statements.

Subexpression Analysis

When faced with subexpressions, such as the following preprocessor directive, ctalk analyzes the statement from the innermost expression outwards:

#if (defined __USE_ISOC99 || \
    (defined __GNUC__ && defined __USE_MISC))

Listing Five shows the function macro_subexpr(), which recursively analyzes subexpressions in preprocessor statements. The variables inner_start and inner_end are message-stack indexes that point to the beginning and end of the subexpression, respectively, excluding the subexpression's parentheses.

Listing Five

int macro_subexpr (MESSAGE **messages, int start_ptr, 
		   int end_ptr) 
{

  int i, inner_start, inner_end, inner_result, result;

  /* Look for an inner set of parentheses and evaluate
     that expression first. */
  if ((inner_start = 
	scanforward (messages, start_ptr - 1, end_ptr, OPENPAREN)) 
      != -1) {
    if ((inner_end = 
	 match_paren (messages, inner_start, end_ptr + 1)) 
	!= -1) {

      inner_result = macro_subexpr (messages, inner_start, 
				    inner_end);

    }
  }

  result = macro_parse (NULL, start_ptr - 1, end_ptr + 1);

  for (i = start_ptr; i >= end_ptr; i--) {
    ++(messages[i] -> evaled);
    messages[i] -> tokentype = PREPROCESS_EVALED;
    sprintf (messages[i] -> value, "%d", result);
  }

  return result;
}

The function macro_parse() is the main preprocessor parser. It analyzes each Boolean subexpression or macro define to TRUE or FALSE. The for() loop at the end of the function sets the statement's message tokens to PREPROCESS_EVALED to signal that the expression does not need to be evaluated again.

The macro_subexpr() function also sets the value of each token in the subexpression to either True or False by setting its message's value member. In the next upper level parser, the following statements can retrieve the value of a subexpression element from its message:

case PREPROCESS_EVALED:
  result = atoi (m -> value);
  break;

Ctalk messages, when evaluated, typically contain values that are more complex than true or false, so to generalize the MESSAGE structure, it contains members for text strings as well as value objects.


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.