首页 > Web开发 > 详细

js语法树转js

时间:2019-07-07 16:14:47      阅读:88      评论:0      收藏:0      [点我收藏+]
//js语法树节点类型-babylon@6.18
const typeMap= {
    ‘File‘:function (node) {
        return [node.program];
    },
    ‘Program‘:function (node) {
        return [node.body]
    },
    ‘CommentBlock‘:function (node) {},
    ‘CommentLine‘:function (node) {},
    ‘VariableDeclaration‘:function (node) {
        return [
            node.kind+‘ ‘,
            node.declarations,
        ];
    },
    ‘VariableDeclarator‘:function (node) {
        if(node.init===null){
            return [
                node.id,
                ‘;‘
            ];
        }
        return [
            node.id,
            ‘=‘,
            node.init,
            ‘;‘
        ];
    },
    ‘Identifier‘:function (node) {
        return node.name;
    },
    ‘CallExpression‘:function (node) {
        return [
            node.callee,
            ‘(‘,
            joinSymbol(node.arguments,‘,‘),
            ‘)‘
        ];
    },
    ‘FunctionDeclaration‘:function (node) {
        return [
            ‘function ‘,
            node.id,
            ‘(‘,
            joinSymbol(node.params,‘,‘),
            ‘)‘,
            node.body,
        ];
    },
    ‘BlockStatement‘:function (node) {
        return [
            ‘{‘,
            node.body,
            ‘}‘,
        ];
    },
    ‘ReturnStatement‘:function (node) {
        return [
            ‘return ‘,
            node.argument||‘‘,
            ‘;‘
        ]
    },
    ‘Literal‘:function (node) {},
    ‘ExpressionStatement‘:function (node) {
        return [
            node.expression,
            ‘;‘
        ]
    },
    ‘Property‘:function (node) {},
    ‘DirectiveLiteral‘:function (node) {},
    ‘Directive‘:function (node) {},

    ‘Decorator‘:function (node) {},
    ‘BreakStatement‘:function (node) {
        return ‘break;‘
    },
    ‘ContinueStatement‘:function (node) {
        return ‘continue;‘
    },
    ‘DebuggerStatement‘:function (node) {
        return ‘debugger;‘
    },
    ‘DoWhileStatement‘:function (node) {
        return [
            ‘do‘,
            node.body,
            ‘while(‘,
            node.test,
            ‘)‘
        ];
    },

    ‘IfStatement‘:function (node) {
        return [
            ‘if(‘,
            node.test,
            ‘)‘,
             node.consequent,
        ];
    },

    ‘SwitchCase‘:function (node) {},
    ‘SwitchStatement‘:function (node) {},
    ‘ThrowStatement‘:function (node) {},
    ‘CatchClause‘:function (node) {},
    ‘TryStatement‘:function (node) {},
    ‘WhileStatement‘:function (node) {
        return [
            ‘while(‘,
            node.test,
            ‘)‘,
            node.body
        ];
    },
    ‘WithStatement‘:function (node) {

    },
    ‘EmptyStatement‘:function (node) {},
    ‘LabeledStatement‘:function (node) {},

    ‘ForStatement‘:function (node) {
        return [
            ‘for(‘,
            node.init,
            ‘;‘,
            node.test,
            ‘;‘,
            node.update,
            ‘)‘,
            node.body,
        ];
    },
    ‘ForInStatement‘:function (node) {
        return [
            ‘for(‘,
            AstToString(node.left).replace(‘;‘,‘‘),
            ‘ in ‘,
            node.right,
            ‘)‘,
            node.body,
        ];
    },

    ‘FunctionExpression‘:function (node) {

        return [
            ‘function (‘,
            joinSymbol(node.params,‘,‘),
            ‘)‘,
            node.body,
        ]
    },
    ‘ClassDeclaration‘:function (node) {},
    ‘ClassExpression‘:function (node) {},
    ‘ClassBody‘:function (node) {},
    ‘ClassProperty‘:function (node) {},
    ‘ClassMethod‘:function (node) {},
    ‘ExportNamespaceSpecifier‘:function (node) {},
    ‘ExportAllDeclaration‘:function (node) {},
    ‘ExportDefaultSpecifier‘:function (node) {},
    ‘ExportDefaultDeclaration‘:function (node) {},
    ‘ExportNamedDeclaration‘:function (node) {},
    ‘ExportSpecifier‘:function (node) {},
    ‘ImportDeclaration‘:function (node) {},
    ‘ImportNamespaceSpecifier‘:function (node) {},
    ‘ImportSpecifier‘:function (node) {},
    ‘ImportDefaultSpecifier‘:function (node) {},
    ‘SpreadElement‘:function (node) {},
    ‘RestElement‘:function (node) {},
    ‘ArrayPattern‘:function (node) {},
    ‘AssignmentPattern‘:function (node) {},
    ‘SequenceExpression‘:function (node) {},
    ‘AssignmentExpression‘:function (node) {
        return [
            node.left,
            node.operator,
            node.right,
        ]
    },
    ‘ConditionalExpression‘:function (node) {},
    ‘LogicalExpression‘:function (node) {
        return [
            node.left,
            node.operator,
            node.right,
        ]
    },
    ‘BinaryExpression‘:function (node) {
        return [
            node.left,
            node.operator,
            node.right,
        ]
    },
    ‘UpdateExpression‘:function (node) {
        return [
            node.argument,
            node.operator,
        ]
    },
    ‘UnaryExpression‘:function (node) {
        if(node.prefix){
            return [
                node.operator,
                node.argument,
            ]
        }
    },
    ‘BindExpression‘:function (node) {},
    ‘MemberExpression‘:function (node) {
        if(node.computed){
            return [
                node.object,
                ‘[‘,
                node.property,
                ‘]‘
            ];
        }
        return [
            node.object,
            ‘.‘,
            node.property,
        ];
    },

    ‘TaggedTemplateExpression‘:function (node) {},
    ‘Super‘:function (node) {},
    ‘Import‘:function (node) {},
    ‘ThisExpression‘:function (node) {
        return ‘this‘;
    },
    ‘DoExpression‘:function (node) {},
    ‘NullLiteral‘:function (node) {
        return ‘null‘;
    },
    ‘BooleanLiteral‘:function (node) {
        return ‘‘+node.value;
    },
    ‘ArrayExpression‘:function (node) {
        return [
            ‘[‘,
            joinSymbol(node.elements,‘,‘),
            ‘]‘
        ]
    },
    ‘StringLiteral‘:function (node) {
        return node.extra.raw;
    },
    ‘NumericLiteral‘:function (node) {
        return node.extra.raw;
    },
    ‘RegExpLiteral‘:function (node) {},
    ‘MetaProperty‘:function (node) {},
    ‘NewExpression‘:function (node) {
        return [
            ‘new ‘,
            node.callee,
            ‘(‘,
            joinSymbol(node.arguments,‘,‘),
            ‘)‘
        ];
    },
    ‘TemplateElement‘:function (node) {},
    ‘TemplateLiteral‘:function (node) {},
    ‘ObjectPattern‘:function (node) {
        return [
            ‘{‘,
            joinSymbol(node.properties,‘,‘),
            ‘}‘,
        ];
    },
    ‘ObjectExpression‘:function (node) {
        return [
            ‘{‘,
            joinSymbol(node.properties,‘,‘),
            ‘}‘,
        ];
    },
    ‘ObjectMethod‘:function (node) {},
    ‘ObjectProperty‘:function (node) {
        if(node.shorthand){
            return [node.value];
        }
        return [
            node.key,
            ‘:‘,
            node.value
        ]
    },
    ‘ArrowFunctionExpression‘:function (node) {},
    ‘AwaitExpression‘:function (node) {
        return [
            ‘await ‘,
            node.argument
        ];
    },
    ‘YieldExpression‘:function (node) {},
    ‘MethodDefinition‘:function (node) {},
    ‘DeclaredPredicate‘:function (node) {},
    ‘InferredPredicate‘:function (node) {},
    ‘DeclareClass‘:function (node) {},
    ‘TypeAnnotation‘:function (node) {},
    ‘DeclareFunction‘:function (node) {},
    ‘DeclareExportDeclaration‘:function (node) {},
    ‘DeclareVariable‘:function (node) {},
    ‘DeclareModule‘:function (node) {},
    ‘DeclareModuleExports‘:function (node) {},
    ‘DeclareTypeAlias‘:function (node) {},
    ‘DeclareOpaqueType‘:function (node) {},
    ‘DeclareInterface‘:function (node) {},
    ‘InterfaceExtends‘:function (node) {},
    ‘InterfaceDeclaration‘:function (node) {},
    ‘TypeAlias‘:function (node) {},
    ‘OpaqueType‘:function (node) {},
    ‘TypeParameterDeclaration‘:function (node) {},
    ‘TypeParameterInstantiation‘:function (node) {},
    ‘ObjectTypeIndexer‘:function (node) {},
    ‘ObjectTypeProperty‘:function (node) {},
    ‘ObjectTypeCallProperty‘:function (node) {},
    ‘ObjectTypeSpreadProperty‘:function (node) {},
    ‘ObjectTypeAnnotation‘:function (node) {},
    ‘QualifiedTypeIdentifier‘:function (node) {},
    ‘GenericTypeAnnotation‘:function (node) {},
    ‘TypeofTypeAnnotation‘:function (node) {},
    ‘TupleTypeAnnotation‘:function (node) {},
    ‘FunctionTypeParam‘:function (node) {},
    ‘AnyTypeAnnotation‘:function (node) {},
    ‘VoidTypeAnnotation‘:function (node) {},
    ‘BooleanTypeAnnotation‘:function (node) {},
    ‘MixedTypeAnnotation‘:function (node) {},
    ‘EmptyTypeAnnotation‘:function (node) {},
    ‘NumberTypeAnnotation‘:function (node) {},
    ‘StringTypeAnnotation‘:function (node) {},
    ‘FunctionTypeAnnotation‘:function (node) {},
    ‘StringLiteralTypeAnnotation‘:function (node) {},
    ‘BooleanLiteralTypeAnnotation‘:function (node) {

    },
    ‘NullLiteralTypeAnnotation‘:function (node) {},
    ‘NumericLiteralTypeAnnotation‘:function (node) {},
    ‘ThisTypeAnnotation‘:function (node) {},
    ‘ExistentialTypeParam‘:function (node) {},
    ‘ArrayTypeAnnotation‘:function (node) {},
    ‘NullableTypeAnnotation‘:function (node) {},
    ‘IntersectionTypeAnnotation‘:function (node) {},
    ‘UnionTypeAnnotation‘:function (node) {},
    ‘TypeCastExpression‘:function (node) {},
    ‘ClassImplements‘:function (node) {},


    ‘JSXEmptyExpression‘:function (node) {},
    ‘JSXSpreadChild‘:function (node) {},
    ‘JSXExpressionContainer‘:function (node) {},
    ‘JSXSpreadAttribute‘:function (node) {},
    ‘JSXAttribute‘:function (node) {},
    ‘JSXIdentifier‘:function (node) {},
    ‘JSXNamespacedName‘:function (node) {},
    ‘JSXMemberExpression‘:function (node) {},
    ‘JSXOpeningElement‘:function (node) {},
    ‘JSXClosingElement‘:function (node) {},
    ‘JSXElement‘:function (node) {},
}
function getStartLine(node1,children,num) {
    const node2=Array.isArray(children)?children[0]:children;
    const linen=node2.loc.start.line-node1.loc.start.line;
    return ‘\n‘.repeat(linen);
}
function getEndLine(node1,children,num=0) {
    const node2=Array.isArray(children)?children[children.length-1]:children;
    const linen=node1.loc.end.line-node2.loc.start.line;
    return ‘\n‘.repeat(linen)+‘ ‘.repeat(node2.loc.end.column-num);
}
//语法树转string
function AstChildToString(children) {
    let str=‘‘;
    children.forEach(function (node) {
        str+=AstToString(node)
    })
    return str;
}
//元素之间添加符号
function joinSymbol(oriArr,symbol) {
    const arr=[];
    oriArr.forEach(function (node,i) {
        arr.push(node);
        if(i<oriArr.length-1){
            arr.push(symbol);
        }
    })
    return arr;
}
//语法树转string
function AstToString(ast){
    if(Object.prototype.toString.call(ast)===‘[object Array]‘){
        return AstChildToString(ast);
    }else if(Object.prototype.toString.call(ast)===‘[object String]‘){
        return ast;
    }

    const arr=typeMap[ast.type](ast);
    let str=‘‘;
    if(Array.isArray(arr)){
        arr.forEach(function (obj) {

            if(typeof obj==‘string‘){
                str=str+obj;
            }else{
                if(obj){
                    str=str+AstToString(obj)
                }else{
                    console.log(str)
                }

            }
        })
    }else{
        str=arr;
    }
    return str;
}
module.exports=AstToString;

 

js语法树转js

原文:https://www.cnblogs.com/caoke/p/11146503.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!