Parse indentation level with PEG.js

后端 未结 3 1515
离开以前
离开以前 2021-02-01 10:20

I have essentially the same question as PEG for Python style indentation, but I\'d like to get a little more direction regarding this answer.

The answer successfully gen

3条回答
  •  暖寄归人
    2021-02-01 10:40

    This example uses the colon (:) in order to separate between an object and a simple letter. That way it can also end with an object, but the colon is required. Like the example in the question it does not take care of ignorable whitespaces (eg. before a colon). It is based on Jakubs Kulhans´ example:

    // do not use result cache, nor line and column tracking
    
    { var indentStack = [], indent = ""; }
    
    Start = Object
    
    Object = Block / Letterline
    
    Block = Samedent id:Letter ':' childs:(
        Newline Indent childs:Object* Dedent {return childs;}
    )* {
        if (childs) {
            var o = {}; o[id] = childs.flat().flat();
            return o;
        } else {
            return id;
        }
    }
    
    Letterline = Samedent letters:Letter+ Newline? {return letters;}
    
    Letter = [a-z]
    
    Newline = "\r\n" / "\n" / "\r"
    
    Indent = &(
        i:[ ]+ &{
            return i.length > indent.length;
        } {
            indentStack.push(indent);
            indent = i.join("");
        }
    )
    
    Samedent = i:[ ]* &{ return i.join("") === indent; }
    
    Dedent = &{ indent = indentStack.pop(); return true; }
    

    The grammar will produce the desired output for the following input:

    a:
      bc
      d:
        zy
        x:
    

提交回复
热议问题