COMP1721 - Higher Computing 1B

Computing 1B - Week 10 Tutorial Solutions


  1. T_INT
    T_IDENTIFIER
    T_SEMICOLON
    T_IDENTIFIER
    T_ASSIGNMENT
    T_CONSTANT
    T_SEMICOLON
    T_PUTI
    T_LEFT_PARENTHESIS
    T_IDENTIFIER
    T_RIGHT_PARENTHESIS
    T_SEMICOLON
    


    For the T_IDENTIFIER tokens the text() will be "answer".

    For the T_CONSTANT token the int_value will be 42.


  2. #include <stdio.h>
    #include <stdlib.h>
    #include "cavy_syntax.h"
    
    char *source_filename;
    
    void usage(char *myname);
    void count_semicolons(void);
    
    void
    usage(char *myname) {
        fprintf(stderr, "Usage: %s [simple-C-file]\n", myname);
        exit(1); 
    }
    
    
    int
    main(int argc, char *argv[]) {
        if (argc == 1) {
            source_filename = "";
            open_lexical_analysis(stdin);
        } else if (argc == 2) {
            FILE *f;
            source_filename = argv[1];
            if ((f = fopen(argv[1], "r")) == NULL) {
                fprintf(stderr, "%s: cannot open file: %s\n", argv[0], source_filename);
                exit(1);
            }
            open_lexical_analysis(f);
        } else {
            usage(argv[0]);
        }
        
        /*
         * code above here is distributed with assignment 2
         */
        count_semicolons();
        return 0;
    }
    void
    count_semicolons(void) {
        int semicolon_count = 0;
    
        for (;;) {
            token *t = get_token();
            if (t->type == T_EOF)
                break;
            if (t->type == T_SEMICOLON)
                semicolon_count++;
        }
        
        printf("%d\n", semicolon_count);
    }
    

  3. typedef struct variable variable;
    
    struct variable {
        char        *name;
        variable    *next;
        int         value;
    };
    /*
     * Find the int variable associated with a name.
     *
     * A pointer to the int variable is returned.
     *
     * If the name has not been previously associated
     * with an int variable, a variable is created
     * and initialized to zero.
     */
    
    int *
    lookup_variable(char *name) {
        static variable *list;
        variable *v;
        
        for (v = list; v != NULL; v = v->next)
            if (strcmp(name, v->name) == 0)
                return &(v->value);
        
        if ((v = malloc(sizeof *v)) == NULL) {
            fprintf(stderr, "Out of memory\n");
            exit(1);
        }
        v->name = name;
        v->next = list;
        v->value = 0;
        list = v;
        return &(v->value);
    }
    


Andrew Taylor (andrewt@cse.unsw.edu.au)
Higher Computing 1B, Computer Science & Engineering, UNSW