如何手工编写(shell)词法分析器

mat*_*eug 5 c shell parsing lexer

我正在研究一个shell,一个像bash一样的小shell,没有脚本(如果......)我必须手工制作lexer/parser(LL).

因此词法分析器会将命令(char*cmd)转换为链表(t_list*list).LL解析器将链接列表(t_list*list)转换为带有语法的AST(二叉树t_btree*root)

所以,我知道如何制作LL解析器,但我不知道如何标记我的命令.

例如: ps | grep ls >> file ; make && ./a.out

=> 'ps' '|' 'grep' 'ls' '>>' 'file' ';' ''make '&&' './a.out'

谢谢.

(我不想使用任何发电机)

ana*_*lyg 6

(这解释了Spudd86暗示的想法).

您需要实现有限状态机.有以下几种状态:

  • 一般国家
  • 在文件名中
  • &&令牌内
  • ||令牌内

对于每个状态和下一个输入字符,您必须确定下一个状态是什么,以及是否输出令牌.例如:

  • 现状:一般 ; character:x => next state:inside-file-name
  • 当前状态:inside-file-name ; character:space => next state:General ; 输出令牌
  • 当前状态:inside-file-name ; character:& => next state:inside - && ; 输出令牌
  • 当前状态:inside - && ; 字符:& =>下一个状态:一般 ; 输出令牌
  • 当前状态:inside - && ; character:x => next state:General ; 语法错误
  • ......(ad nauseum)

解决所有规则是非常无聊的工作(当你必须调试生成的代码时开始有趣),所以大多数人使用代码生成器来做到这一点.


编辑:一些代码(抱歉,如果语法混乱;我通常用C++编程)

enum state {
    STATE_GENERAL,
    STATE_IN_FILENAME,
    ...
};

// Many characters are treated the same (e.g. 'x' and 'y') - so use categories
enum character_category
{
    CHAR_GENERAL, // can appear in filenames
    CHAR_WHITESPACE = ' ',
    CHAR_AMPERSAND = '&',
    CHAR_PIPE = '|',
    CHAR_EOF = EOF,
    ...
};

character_category translate(int c)
{
    switch (c) {
    case '&': return CHAR_AMPERSAND;
    case ' ': case '\t': case '\n': return CHAR_WHITESPACE;
    ...
    default: return CHAR_GENERAL;
    }
}

void do_stuff()
{
    character_category cat;
    state current_state = STATE_GENERAL;
    state next_state;
    char token[100];
    char token_length = 0;
    do {
        int c = getchar();
        cat = translate(c);
        // The following implements a switch on 2 variables
        int selector = 1000 * current_state + cat;

        switch (selector)
        {
        case 1000 * STATE_GENERAL + CHAR_GENERAL:
            next_state = STATE_IN_FILENAME;
            token[token_length++] = c; // append a character to a filename token
            break;

        case 1000 * STATE_GENERAL + CHAR_WHITESPACE:
            next_state = STATE_GENERAL; // do nothing
            break;

        case 1000 * STATE_GENERAL + CHAR_PIPE:
            next_state = STATE_IN_OR_TOKEN; // the first char in '||' or just '|'
            break;

        // Much repetitive code already; define a macro for the case constants?
        // Have to cover all states and all character categories; good luck...

        case 1000 * STATE_IN_FILENAME + EOF:
        case 1000 * STATE_IN_FILENAME + CHAR_WHITESPACE:
            next_state = STATE_GENERAL;
            printf("Filename token: %s\n", token);
            break;

        default:
            printf("Bug\n"); // forgot one of the cases?
        }

        current_state = next_state;

    } while (cat != CHAR_EOF);
}
Run Code Online (Sandbox Code Playgroud)