编程杂谈

特别说明:本文生成节点时,函数的使用对于Js来说是错误的(不能指定参数给值),这样写是方便看节点属性思路标识符一般都是有语义的,把标识符无语义化,那么分析难度就会再次增加使用scope.getOwnBinding()例如:在Program节点下,可以获取全局的标识符,而函数内部的标识符名获取不到,要获取局部的的标识符,可以遍历局部节点()的标识符,这样就获取的是函数局部的标识符。标识符混淆letrenameOwnBinding=function(path){letownBindingObj={},//存放binding对象,重名时需要globalBindingObj={},//i=0;//先获取标识符作用域path.traverse({Identifier(p){letname=p.node.name;letbinding=p.scope.getOwnBinding(name)//当前标识符当前节点的绑定binding?(ownBindingObj[name]=binding):(globalBindingObj[name]=1)}})for(letoldNameinownBindingObj){do{varnewName='_0xsdc2d'+i++;}while(globalBindingObj[newName]);//防止与全局标识符混淆变量名重复ownBindingObj[oldName].scope.rename(oldName,newName);}}traverse(ast,{'Program|FunctionExpression|FunctionDeclaration'(path){//酌情增加节点renameOwnBinding(path);}})在进行以再次加密一遍标识符随机生成上面的标识符混淆,还是能看着不是太混乱,我们在继续混乱一点letgeneratorIdentifier=function(decNum){letflag=['O','o','0']letretval=[]while(decNum>0){retval.push(decNum&3)decNum=parseInt(decNum/3)}letIdentifier=retval.reverse().map(function(v){returnflag[v]}).join('')Identifier.length<6?(Identifier=('OOOOOO'+Identifier).substr(-6)):Identifier[0]=='0'&&(Identifier='O'+Identifier)returnIdentifier}//修改上面的生成标识符的地方//varnewName='_0xsdc2d'+i++;varnewName=generatorIdentifier(i++);

编程杂谈

特别说明:本文生成节点时,函数的使用对于Js来说是错误的(不能指定参数给值),这样写是方便看节点属性说明【AST混淆】一、常量&标识符的混淆之后,虽然字符串已经加密了,但是依旧在原来的位置,数组混淆,就是要把这些字符串提取到数组中,然后字符串原先的位置改用数组下标的方式去访问数值成员,字符串还能提取到多个数组,不同的数组处于不同的作用域。//混淆前atob("RGF0ZQ==")//混淆后letarr=["RGF0ZQ=="]atob([0]])使用例子window[atob("RGF0ZQ==")][atob("cHJvdG90eXBl")][atob("Zm9ybWF0")]=function(formatSTr){varstr=formatSTr;varweek=[atob("5pel"),atob("5LiA"),atob("5LqM"),atob("5LiJ"),atob("5Zub"),atob("5LqU"),atob("5YWt")];str=str[atob("cmVwbGFjZQ==")](/yyyy|YYYY/,this[atob("Z2V0RnVsbFllYXI=")]());str=str[atob("cmVwbGFjZQ==")](/MM/,this[atob("Z2V0TW9udGg=")]()+1>9?(this[atob("Z2V0TW9udGg=")]()+1)[atob("dG9TdHJpbmc=")]():atob("MA==")+(this[atob("Z2V0TW9udGg=")]()+1));str=str[atob("cmVwbGFjZQ==")](/dd|DD/,this[atob("Z2V0RGF0ZQ==")]()>9?this[atob("Z2V0RGF0ZQ==")]()[atob("dG9TdHJpbmc=")]():atob("MA==")+this[atob("Z2V0RGF0ZQ==")]());returnstr;};window[atob("Y29uc29sZQ==")][atob("bG9n")](newwindow[atob("RGF0ZQ==")]()[atob("Zm9ybWF0")](atob("eXl5eS1NTS1kZA==")));数组混淆letbigArr=[];//存字符串大数组traverse(ast,{StringLiteral(path){letvalue=path.node.value;//获取值letbigArrIndex=bigArr.indexOf(value);//判断字符串是否再大数据letindex=bigArrIndex;if(bigArrIndex==-1){//添加字符串到大数据letlength=bigArr.push(value);index=length-1;}path.replaceWith(//字符串替换成调用表达式type.memberExpression(object=type.identifier('arr'),property=type.numericLiteral(value=index),computed=true))}})//把大数组组合成节点添加到代码头部bigArr=bigArr.map((v)=>{returntype.stringLiteral(v)})bigArr=type.variableDeclarator(id=type.identifier('arr'),init=type.arrayExpression(bigArr))bigArr=type.variableDeclaration(kind='var',declarations=[bigArr])//大数组添加到头部ast.program.body.unshift(bigArr)实现数组乱序上面实现的数组混淆,数组元素与索引之间是一一对应的,那如果数组元素与索引之间还需要函数进行转换,运行时,才把大数据还原到正确顺序,那样难度就会再上升。乱序函数&还原函数//乱序函数((arr,nums)=>{while(--nums){//简单的倒序arr.unshift(arr.pop())}})(this.bigArr,this.bigArr.length)//还原函数((arr,nums)=>{while(--nums){//再倒回来arr.push(arr.shift())}})(arr,arr.length)添加到代码头部还原函数要在乱序数组之后this.bigArr=type.variableDeclarator(id=type.identifier('arr'),init=type.arrayExpression(this.bigArr))this.bigArr=type.variableDeclaration(kind='var',declarations=[this.bigArr])this.codeAst&&this.ast.program.body.unshift(this.codeAst)//把解密函数添加到头部this.ast.program.body.unshift(this.bigArr)//大数组添加到头部完整代码arrayEncrypt=function(ast){//数组混淆,把字符串提取到一个大数组letbigArr=[];//存字符串大数组traverse(ast,{StringLiteral(path){letvalue=path.node.value;//获取值letbigArrIndex=bigArr.indexOf(value);//判断字符串是否再大数据letindex=bigArrIndex;if(bigArrIndex==-1){//添加字符串到大数据letlength=bigArr.push(value);index=length-1;}path.replaceWith(//字符串替换成调用表达式type.memberExpression(object=type.identifier('arr'),property=type.numericLiteral(value=index),computed=true))}})//把大数组组合成节点添加到代码头部bigArr=bigArr.map((v)=>{returntype.stringLiteral(v)})this.bigArr=bigArr;//为数组乱序做准备this.ast=ast;//把数组和顺序还原函数添加到头部做准备returnthis}arrayEncrypt.prototype.arrayShuffle=function(){//打乱大数组函数((arr,nums)=>{while(--nums){arr.unshift(arr.pop())}})(this.bigArr,this.bigArr.length)//读取解密函数//letcode=fs.readFileSync('./utils/confountArray.js',{encoding:"utf-8"})//解密函数太长可以单独放在一个文件里letcode='((arr,nums)=>{while(--nums){arr.push(arr.shift())}})(arr,arr.length)'this.codeAst=parser.parse(code);returnthis}arrayEncrypt.prototype.unshiftArrayDeclaration=function(){//合并大数据&还原函数this.bigArr=type.variableDeclarator(id=type.identifier('arr'),init=type.arrayExpression(this.bigArr))this.bigArr=type.variableDeclaration(kind='var',declarations=[this.bigArr])this.codeAst&&this.ast.program.body.unshift(this.codeAst)//把解密函数添加到头部this.ast.program.body.unshift(this.bigArr)//大数组添加到头部returnthis}//打乱数组newarrayEncrypt(ast).arrayShuffle().unshiftArrayDeclaration()//不打乱数组//newarrayEncrypt(ast).unshiftArrayDeclaration()实现十六进制字符串上面的数组混淆,其中的还原函数的函数没有办法提取到大数组中,但其中的push、shift这些方法都可以转换成字符串,简单的编码成十六进制字符串arrayEncrypt.prototype.stringToHex=function(){lethexEnc=function(code){for(varhexStr=[],i=0,s;i<code.length;i++){s=code.charCodeAt(i).toString(16);hexStr+='\\x'+s;//bable会自动处理转义字符,所以生成时,反斜杠会多,最后生成代码时要替换掉}returnhexStr;}traverse(this.ast,{MemberExpression(path){if(type.isIdentifier(path.node.property)){letname=path.node.property.name;path.node.property=type.stringLiteral(hexEnc(name))}path.node.computed=true;}});returnthis}newarrayEncrypt(ast).arrayShuffle().unshiftArrayDeclaration().stringToHex()//newarrayEncrypt(ast).unshiftArrayDeclaration().stringToHex()//ast转化为代码letcode=generator(ast).codecode=code.replace(/\\\\x/g,'\\x')//替换掉十六进制多余的转义字符

编程杂谈

特别说明:本文生成节点时,函数的使用对于Js来说是错误的(不能指定参数给值),这样写是方便看节点属性使用例子Date.prototype.format=function(formatSTr){varstr=formatSTr;str=str.replace(/yyyy|YYYY/,this.getFullYear())str=str.replace(/MM/,(this.getMonth()+1)>9?(this.getMonth()+1).toString():'0'+(this.getMonth()+1));str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():'0'+this.getDate())returnstr}console.log(newDate().format('yyyy-MM-dd'))实现数值常量的加密NumberLiteral节点:value->BinaryExpression节点:cipherNum^key代码中的数值常量可以遍历NumberLiteral,获取其中的value属性得到,然后随机生成一个Key,把Key和Value进行异或,得到加密后的cipherNum,即cipherNum=value^key,这样就可以用BinaryExpression节点等价的替换NumberLiteral节点/*加密数值常量:1-->343333^343332cipherNum=value^keyvalue=cipherNum^key*/traverse(ast,{NumericLiteral(path){letvalue=path.node.value;letkey=parseInt(Math.random()*(999999-100000),10)letcipherNum=value^key;path.replaceWith(type.binaryExpression('^',left=type.numericLiteral(value=cipherNum),right=type.numericLiteral(value=key)))//替换节点里也有NumericLiteral节点,会造成死循环,因此需要加入path.skip()path.skip()}})实现字符串常量的加密字符串常量的加密,是使用一个加密函数,对字符串进行加密,在使用时,又解密成原始字符串先遍历StringLiteral节点,获取value属性,然后对value进行加密,把StringLiteral节点替换成CallExpression节点(调用表达式)例子这里的例子,需要改变一下,把调用方法使用之前的文章,改成字符串调用的方式window["Date"]["prototype"]["format"]=function(formatSTr){varstr=formatSTr;str=str["replace"](/yyyy|YYYY/,this["getFullYear"]());str=str["replace"](/MM/,this["getMonth"]()+1>9?(this["getMonth"]()+1)["toString"]():'0'+(this["getMonth"]()+1));str=str["replace"](/dd|DD/,this["getDate"]()>9?this["getDate"]()["toString"]():'0'+this["getDate"]());returnstr;};window["console"]["log"](newwindow["Date"]()["format"]('yyyy-MM-dd'));加密对字符串进行base64编码,然后浏览器在运行时,调用atob再解码encFun=(str)=>{returnBuffer.from(str,'utf-8').toString('base64');}traverse(ast,{StringLiteral(path){letstr=path.node.value;letencStr=encFun(path.node.value);path.replaceWith(type.callExpression(callee=type.identifier(value='atob'),//atob()不支持中文解码_arguments=[type.stringLiteral(value=encStr)]))//替换节点里也有stringLiteral节点,会造成死循环,因此需要加入path.skip()path.skip();}})

编程杂谈

scope作用域scope提供了一些属性和方法使用的例子consta=1000;letb=2000;letobj={name:'haha',add:function(a){a=400;b=300;lete=700;functiondemo(){letb=600;}demo();returna+a+b+1000+obj.name}}obj.add(100)获取’标识符’作用域path.scope.block()可以获取标识符作用域,返回Node对象visitor={Identifier(path){if(path.node.name==='e'){//e的作用域就是整个函数console.log(generator(path.scope.block).code)}}}traverse(ast,visitor)/*function(a){a=400;b=300;lete=700;functiondemo(){letb=600;}demo();returna+a+b+1000+obj.name;}*/但有时候作用域输出的范围与实际不符合,就需要获取父节点的作用visitor={FunctionDeclaration(path){//函数声明只有demo()满足要求console.log(generator(path.scope.block).code)}}traverse(ast,visitor)/*functiondemo(){letb=600;}*/demo()的作用域实际上应该是整个add()的范围,这时就与实际输出不符合,就需要获取父节点的作用域visitor={FunctionDeclaration(path){console.log(generator(path.scope.parent.block).code)}}traverse(ast,visitor)/*function(a){a=400;b=300;lete=700;functiondemo(){letb=600;}demo();returna+a+b+1000+obj.name;}*/path.scope.getBinding获取标识符对应的绑定对象(Binding)visitor={FunctionDeclaration(path){letbinding=path.scope.getBinding('a')console.log(binding)}}traverse(ast,visitor)/*Binding{identifier:Node{type:"Identifier",start:83,end:84,loc:SourceLocation,name:"a"},//标识符的Node对象scope:Scope{uid:1,path:NodePath,block:Node,labels:Map(0),inited:true,...},//对应标识符的scope对象path:NodePath{contexts:Array(0),state:Object,opts:Object,_traverseFlags:0,skipKeys:null,...},//对应标识符的Path对象kind:"param",//该标识符类型这里表示是一个参数constantViolations:Array(1)[NodePath],//存放修改了该标识符的节点constant:false,//是否是常量referencePaths:Array(2)[NodePath,NodePath],//引用了该标识符的NodePath数组referenced:true,//该标识符是否被引用references:2,//该标识符的引用次数hasDeoptedValue:false,//hasValue:false,value:null}*/referencePaths&constantViolations这两个是Binding对象里的属性/*Binding{...referencePaths:Array(2)[NodePath,NodePath],//引用了该标识符的NodePath数组,没有引用时为空数组constantViolations:Array(1)[NodePath],//存放修改了该标识符的节点,没有被修改时为空数组...}*/遍历作用域有两种方式遍历作用域path.scope.traverse({})binding.scope.traverse({}):推荐//path.scope.traverse({})visitor={FunctionExpression(path){letbinding=path.scope.traverse({Identifier(path){console.log('')}})}}traverse(ast,visitor)//binding.scope.traverse({})推荐visitor={FunctionExpression(path){letbinding=path.scope.getBinding('a')binding.scope.traverse({Identifier(path){console.log('')}})}}traverse(ast,visitor)把例子函数中的a=400改成a=60visitor={FunctionExpression(path){letbinding=path.scope.getBinding('a')binding.scope.traverse(path.scope.block,{//遍历a的作用域AssignmentExpression(path){if(path.node.left.name==='a'){path.node.right=type.valueToNode(60)}}})}}traverse(ast,visitor)标识符重命名binding.scope.rename()该方法,会重命名所有引用了该标识符的地方visitor={FunctionExpression(path){letbinding=path.scope.getBinding('b')binding&&binding.scope.rename('b','xx')}}traverse(ast,visitor)/*consta=1000;letb=2000;letobj={name:'haha',add:function(xx){//a-->xxxx=400;//函数的参数a-->xxb=300;lete=700;functiondemo(){letb=600;}demo();returnxx+xx+b+1000+obj.name;}};obj.add(100);*/随机生成标识符path.scope.generateUidIdentifier('_0xoO').name该方法会生成一个字符串且不会重复可以用来实现简单的标识符混淆,也可以用来反混淆,使变量看起来好分析visitor={Identifier(path){path.scope.rename(path.node.name,path.scope.generateUidIdentifier('_0xoO').name)}}traverse(ast,visitor)/*const_0xoO=1000;let_0xoO15=2000;let_0xoO18={name:'haha',add:function(_0xoO14){_0xoO14=400;_0xoO15=300;let_0xoO9=700;function_0xoO12(){let_0xoO11=600;}_0xoO12();return_0xoO14+_0xoO14+_0xoO15+1000+_0xoO18.name;}};_0xoO18.add(100);*/scope其他方法path.scope.hasBinding('a')返回值是bool值,作用是查询该作用域是否有该标识符的绑定该方法可以用path.scope.getBinding('a')代替,只是该方法的返回值是undefined和Binding{}visitor={Identifier(path){console.log(path.scope.hasBinding('a'))}}traverse(ast,visitor)/*true...*/path.scope.getAllBindings()获取该节点的所有绑定,返回的对象以标识符名为属性名,对应的属性是Binding{..}visitor={Identifier(path){console.log(path.scope.getAllBindings())}}traverse(ast,visitor)/*Object{a:Binding{..},b:Binding{..},obj:Binding{..}}*/path.scope.hasReference('a')查询当前节点是否有标识符a的引用,返回值是true/false

编程杂谈

Path对象Path&Node的区别Path是描述父子节点之间的链接,Path除了下面这些属性外,还包含添加、更新、移动、删除等方法Node对象是Path对象中的一个属性。path.node能取出当前遍历到的节点各种具体信息,不能使用Path对象的各种方法/*NodePath{contexts:Array(1)[TraversalContext],//上下文内容嵌套自己state:undefined,opts:Object{Identifier:Object,_exploded:true,_verified:true},_traverseFlags:0,skipKeys:null,parentPath:NodePath{contexts:Array(1),state:undefined,opts:Object,_traverseFlags:0,skipKeys:null,...},//父节点Path对象container:Node{type:"VariableDeclarator",start:4,end:162,loc:SourceLocation,id:Node,...},//容器里面是兄弟节点,有数组(有兄弟)和单个对象(没有兄弟)listKey:undefined,//有兄弟节点时,兄弟节点的容器的名字key:"id",//有兄弟节点时,代表兄弟容器索引,没有兄弟节点,代表对象属性名node:Node{type:"Identifier",start:4,end:7,loc:SourceLocation,name:"obj"},//Node对象type:"Identifier",parent:Node{type:"VariableDeclarator",start:4,end:162,loc:SourceLocation,id:Node,...},//父节点Node对象hub:undefined,data:null,context:TraversalContext{queue:Array(1),priorityQueue:Array(0),parentPath:NodePath,scope:Scope,state:undefined,...},scope:Scope{uid:0,path:NodePath,block:Node,labels:Map(0),inited:true,...},//作用域}*/Path对象中的方法获取当前节点为了获取到AST节点的属性值,需要先访问到该节点,然后用path.node.xxx(xxx相关属性)获取获取Node对象letvisitor={Identifier(path){console.log(path.node)//获取当前节点Node对象console.log(path.node.left)//获取Node节点具体属性值}}获取Path对象,但是有些属性值就没有必要包装operator、name…letvisitor={BinaryExpression(path){console.log(path.get('node'))//会把node包装成Path对象返回console.log(path.get('node.left'))//支持多级访问}}判断Path类型letvisitor={BinaryExpression(path){console.log(path.get('left').isIdentifier())console.log(path.get('right').isNumericLiteral({value:1000}))console.log(path.get('left').assertIdentifier())}}/*falsetrue报错*/节点转代码代码比较复杂,需要动态调试,就可以使用该方法,方便查看某一小段代码,就不需要到最后才全部再转换成代码,再看letvisitor={FunctionExpression(path){console.log(generator(path.node).code)console.log(path.toString())//因为Path对象,重写了toString()方法}}/*function(a,b){returna+b+1000;}function(a,b){returna*b+1000;}*/替换节点属性替换需要属性,需要符合实际逻辑,在允许的范围替换,不能随便替换,造成逻辑错误visitor={BinaryExpression(path){path.node.left=type.identifier(name="x")path.node.right=type.identifier(name="y")}}/*add:function(a,b){returnx+y;},mul:function(a,b){returnx+y;}*/替换节点replaceWith()使用一个节点替换一个节点,一对一的替换visitor={BinaryExpression(path){path.replaceWith(type.valueToNode('mimi'))}}/*add:function(a,b){return"mimi";},mul:function(a,b){return"mimi";}*/replaceWithMultiple()为多个节点替换一个节点两点特别说明:当替换的表达式替换后在一行时,最好使用type.expressionStatement()包裹一层新替换的节点traverse()也会去遍历,所以注意别陷入不合理的递归死循环遍历ReturnStatement()替换,替换里又有ReturnStatement(),陷入递归死循环,所以使用path.stop()停止visitor={ReturnStatement(path){path.replaceWithMultiple([type.expressionStatement(type.valueToNode('ZZ')),type.expressionStatement(type.valueToNode('XX')),type.returnStatement(type.valueToNode('YY')),])path.stop();}}traverse(ast,visitor)/*add:function(a,b){"ZZ";"XX";return"YY";},*/replaceInline(),接受一个参数,作用相对于是replaceWith()replaceWithMultiple()的综合当接受的参数是一个节点,就是replaceWith()当接受的参数是一个节点数组,就是replaceWithMultiple()添加有path.stop()的原因与上面一样visitor={StringLiteral(path){path.replaceInline(type.valueToNode('Hellemimi'))path.stop()},ReturnStatement(path){path.replaceInline([type.expressionStatement(type.valueToNode('ZZ')),type.expressionStatement(type.valueToNode('XX')),type.returnStatement(type.valueToNode('YY')),])path.stop()}}traverse(ast,visitor)replaceWithSourceString()接受字符串作为参数,然后解析到AST里面replaceWithSourceString()替换后的节点也会被解析,所以也需要path.stop()防止陷入递归死循环//把函数改为`闭包形式`visitor={ReturnStatement(path){letargumentPath=path.get('argument')argumentPath.replaceWithSourceString('function(){return'+argumentPath+'}'//字符串拼接会自动调用toString())path.stop()}}/*add:function(a,b){returnfunction(){returna+b+1000;};},*/删除节点visitor={EmptyStatement(path){//空语句也就是多余的分号path.remove()}}traverse(ast,visitor)插入节点插入兄弟节点insertAfter()当前节点之前,insertBefore()当前节点之后如果要操作ReturnStatement,可以先判断,直接return,注意该是用path.stop()是不行的visitor={ReturnStatement(path){path.insertAfter(type.valueToNode("XX"))path.insertBefore(type.valueToNode('MM'));}}traverse(ast,visitor)父级Path在Path对象中有两个属性parentPath、parent,其中parentPath是NodePath类型,是父级的Path对象,parent是父级的Node对象path.findParent&path.find参数都是一个函数,返回值是Path对象,没有找到返回null从当前节点,一直向上遍历,知道满足对应条件path.findParent()常用,查找范围不包含当前节点path.find()不常用,查找范围包含当前节点visitor={ReturnStatement(path){console.log(path.findParent((path)=>{returnpath.isObjectExpression()}))}}/*NodePath{...}*/path.getFunctionParent向上查找与当前节点最接近的父函数节点,返回值是Path对象visitor={ReturnStatement(path){console.log(path.getFunctionParent())}}traverse(ast,visitor)/*NodePath{...}NodePath{...}*/path.getStatementParent向上遍历找到父语句节点,如:return,if,whitch,while…visitor={ReturnStatement(path){console.log(path.getStatementParent())//会从当前节点开始//console.log(path.parentPath.getStatementParent())//取巧}}traverse(ast,visitor)其他方法替换path.parentPath.replaceWith()path.parentPath.replaceWithMultiple()path.parentPath.replaceInline()path.parentPath.replaceWithSourceString()删除path.parentPath.remove()同级节点了解同级节点,首要了解Path对象的这几个属性:container、listKey、keycontainer:有兄弟节点时,是兄弟节点数组,没有兄弟节点时就是当前节点Node对象listKey:有兄弟节点时,为容器名字,没有时是undefinedkey:有兄弟节点时,为当前节点,在容器中的索引,没有时,是当前节点属性名相关属性visitor={ReturnStatement(path){console.log(path.inList)//trueconsole.log(path.listKey)//bodyconsole.log(path.key)//0console.log(path.container)//[Node{...}]}}traverse(ast,visitor)获取兄弟节点path.getSibling参数是容器中节点的索引,visitor={ReturnStatement(path){console.log(path.getSibling(path.key))//Node{...}}}traverse(ast,visitor)网容器添加节点path.parentPath.unshiftContainer():在容器头部添加节点path.parentPath.pushContainer():在容器尾部添加节点添加之后的节点,也会再进行遍历,所以还是需要path.stop(),以防止进入递归死循环visitor={Property(path){path.parentPath.unshiftContainer(path.listKey,[type.objectProperty(key=type.identifier(name="unshift"),//第一个属性value=type.stringLiteral(value="OOO"))//第一个属性值)])path.parentPath.pushContainer(path.listKey,[type.objectProperty(key=type.identifier(name="push"),//第一个属性value=type.stringLiteral(value="MMM"))//第一个属性值)])path.stop()}}traverse(ast,visitor)

编程杂谈

types组件types能用于节点类型的判断和节点的生成,但是主要还是用来节点的生成,因为节点类型的判断可以不用该组件,也能实现类型判断//其他类型也是一样type.isIdentifier(path.node)//相当于path.node.type==='Identifier'type.isIdentifier(path.node,{'name':'x'})//相当于path.node.type==='Identifier'&&path.node.name==='x'节点生成生成实例代码constfs=require('fs')consttype=require("@babel/types")constgenerator=require("@babel/generator").default//AST转换为代码letobjPro1=type.objectProperty(key=type.identifier(name="name"),//第一个属性value=type.stringLiteral(value="haha"))//第一个属性值letbojPro2=type.objectProperty(key=type.identifier(name="add"),value=type.functionExpression(//函数节点id=null,params=[type.identifier(name="a"),type.identifier(name="b")],//参数列表body=type.blockStatement(//函数体body=[type.returnStatement(//返回值argument=type.binaryExpression(//二项式operator="+",left=type.binaryExpression(operator="+",left=type.identifier(name="a"),right=type.identifier(name="b")),right=type.numericLiteral(value=1000)))])))letbojPro3=type.objectProperty(key=type.identifier(name="mul"),//第三个属性value=type.functionExpression(//第三个属性值id=null,params=[type.identifier(name="a"),type.identifier(name="b")],body=type.blockStatement(body=[type.returnStatement(argument=type.binaryExpression(operator="+",left=type.binaryExpression(operator="*",left=type.identifier(name="a"),right=type.identifier(name="b")),right=type.numericLiteral(value=1000)))])))letobj=type.objectExpression([objPro1,bojPro2,bojPro3])//变量初始化letletDec=type.variableDeclarator(type.identifier(name="obj"),init=obj)//变量名letlocalAst=type.variableDeclaration("let",[letDec])//声明变量//ast转化为代码letcode=generator(localAst).codefs.writeFile("./output/code.js",code,(err=>{}))上面使用到stringLiteral、numericLiteraltypes还提供了其他字面量,按照语法树来,都是差不多的declarefunctionstringLiteral(value:string):StringLiteral;declarefunctionnumericLiteral(value:number):NumericLiteral;declarefunctionnullLiteral():NullLiteral;declarefunctionbooleanLiteral(value:boolean):BooleanLiteral;declarefunctionregExpLiteral(pattern:string,flags?:string):RegExpLiteral;当界面量太多,太复杂的时候,Bable也提供了一个简便的方式valueToNode()//可以看出valueToNode可以很方便的生成其他类型exportfunctionvalueToNode(value:undefined):IdentifierexportfunctionvalueToNode(value:boolean):BooleanLiteralexportfunctionvalueToNode(value:null):NullLiteralexportfunctionvalueToNode(value:string):StringLiteralexportfunctionvalueToNode(value:number):NumericLiteral|BinaryExpression|UnaryExpressionexportfunctionvalueToNode(value:RegExp):RegExpLiteralexportfunctionvalueToNode(value:ReadonlyArray<undefined|boolean|null|string|number|RegExp|object>):ArrayExpressionexportfunctionvalueToNode(value:object):ObjectExpressionexportfunctionvalueToNode(value:undefined|boolean|null|string|number|RegExp|object):Expressionconsole.log(generator(type.valueToNode(123)).code)console.log(generator(type.valueToNode('mimi')).code)console.log(generator(type.valueToNode(undefined)).code)console.log(generator(type.valueToNode(null)).code)/*123"mimi"undefinednull*/

编程杂谈

parse&generator组件parse作用是代码转化为AST结构解析网站:https://astexplorer.net/constparser=require("@babel/parser");//需要导入letast=parser.parse(js_code)//代码转化为ast结构,与网站上一样letast1=parser.parse(js_code,{sourceType:"module",//如果有importexport关键字,需要使用该参数})console.log(JSON.stringify(ast,null,2))generator作用是AST结构转化为代码letcode=generator(ast).codeletcode1=generator(ast,{retainLines:false,//默认false,是否输出与源代码相同的行号comments:false,//默认true,是否保留注释compact:true//默认false,是否压缩代码}).codetraverse&visitor组件traverse用来遍历AST结构的节点,简单点说就是把所有节点都运行一遍traverse使用的深度优先策略//导入consttraverse=require("@babel/traverse").default;//遍历节点constgenerator=require("@babel/generator").default//AST转换为代码//相关操作letvisitor={}visitor.FunctionExpression=function(path){console.log("mmmmm")}traverse(ast,visitor)/*源码有两个函数节点所以输出两次mmmmmmmm*/visitor三种写法按照自己的喜好选择,最常用的visitor2letvisitor1={FunctionExpression:function(path){console.log('...')}}letvisitor2={FunctionExpression(path){console.log('...')}}letvisitor3={FunctionExpression:{enter(path){console.log('进入->函数节点')},exit(path){console.log('退出<-函数节点')}}}traverse(ast,visitor3)visitor组合写法使用|组合不同的类型letvisitor1={'FunctionExpression|BinaryExpression':function(path){console.log('...')}}letvisitor2={'FunctionExpression|BinaryExpression'(path){console.log('...')}}letvisitor3={'FunctionExpression|BinaryExpression':{enter(path){console.log('进入->节点')},exit(path){console.log('退出<-节点')}}}traverse(ast,visitor3)使用多个函数处理节点,会按照函数顺序执行functionfun1(path){console.log('11')}functionfun2(path){console.log('22')}letvisitor={FunctionExpression:{enter:[fun1,fun2]}}traverse(ast,visitor)traverse并非必须从头遍历//修改函数第一个参数为x,并修改函数内所有用了该参数的地方constupdateParamNameVisitor={Identifier(path){if(path.node.name===this.paramName){path.node.name="x"}}}constvisitor={FunctionExpression(path){//遍历函数节点constparamName=path.node.params[0].name//内部循环path.traverse(updateParamNameVisitor,{paramName//向子循环传递参数})}}traverse(ast,visitor)

编程杂谈

说明思想:用Miniconda管理多个Python版本,在使用poetry创建虚拟环境的时候,指定Miniconda环境里的Py版本使用前的准备安装Miniconda链接:https://docs.conda.io/en/latest/miniconda.html安装poetry链接:https://bigdataboy.cn/post-399.html创建环境使用Miniconda创建多个Py版本的环境创建不同Python版本的虚拟环境condacreate-nPy3.9python=3.9查看环境condaenvlist使用第一步初始化poetry,使用命令:poetryinit,如果不是新项目直接跳到第二步这里有个坑,poetry指定Py版本的时候,只好写成这种格式~3.8(支持3.8.<3.9.0),不然会报版本不一致的错误,原因就是conda下载的版本是3.8.x,两处版本支持范围要严格一直F:\Tools\pyCode\test>poetryinitThiscommandwillguideyouthroughcreatingyourpyproject.tomlconfig.Packagename[test]:Version[0.1.0]:Description[]:Author[‘zbigdataboy‘<876545500@qq.com>,ntoskip]:bigdataboyLicense[]:CompatiblePythonversions[^3.9]:~3.8Wouldyouliketodefineyourmaindependenciesinteractively?(yes/no)[yes]noWouldyouliketodefineyourdevelopmentdependenciesinteractively?(yes/no)[yes]noGeneratedfile[tool.poetry]name="test"version="0.1.0"description=""authors=["bigdataboy"][tool.poetry.dependencies]python="~3.8"[tool.poetry.dev-dependencies][build-system]requires=["poetry-core>=1.0.0"]build-backend="poetry.core.masonry.api"Doyouconfirmgeneration?(yes/no)[yes]yes第二步peotry使用指定的解释器如果报版本不一致的错误,看第一步的坑poetryenvuseD:\ProgramData\miniconda3\envs\Py3.8\python.exe第三步安装相关依赖poetryinstall

Python极客

说明poetry是一个Python虚拟环境和依赖管理的工具,oetry和pipenv类似,另外还提供了打包和发布的功能。安装安装不成功,大多数是网站被墙了macOS&Linuxcurl-sSLhttps://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py|python-windows在powershell使用该命令(Invoke-WebRequest-Urihttps://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py-UseBasicParsing).Content|python-会自动添加到环境变量,需要重新打开powershell,查看是否安装成功配置使用前修改这些配置后,更好用查看当前配置poetryconfig--list-------------------PSC:\Users\ASUS>poetryconfig--listcache-dir="D:\\Python\\peotry_env"experimental.new-installer=trueinstaller.parallel=truevirtualenvs.create=truevirtualenvs.in-project=truevirtualenvs.path="{cache-dir}\\virtualenvs"#D:\Python\peotry_env\virtualenvs修改配置poetryconfigcache-dirD:\\Python\\peotry_envpoetryconfigvirtualenvs.in-projecttrue创建项目该命令,会建立一个目录结构poetrynewdemo结构demo├──pyproject.toml├──README.rst├──demo│└──__init__.py└──tests├──__init__.py└──test_demo.py其中pyproject.toml文件将协调项目及其依赖项[tool.poetry]name="demo"version="0.1.0"description=""authors=["‘zbigdataboy‘<876545500@qq.com>"][tool.poetry.dependencies]python="^3.9"[tool.poetry.dev-dependencies]pytest="^5.2"[build-system]requires=["poetry-core>=1.0.0"]build-backend="poetry.core.masonry.api"初始化项目这是在项目已经存在的情况下使用,为了创建pyproject.toml管理项目poetryinit添加依赖&库如果项目不存在虚拟环境,将会创建,同时还会创建poetry.lock,用以记录项目依赖的版本poetryaddrequests卸载依赖poetryremoverequests安装依赖项用以使用项目时,依赖于开发时一样poetryinstall修改依赖安装源项目的pyproject.toml文末追加[[tool.poetry.source]]name="tsinghua"url="https://pypi.tuna.tsinghua.edu.cn/simple"虚拟环境执行项目poetry会自动在相应目录寻找该项目的环境poetryrunpythonapp.py显示的激活poetryshell其他命令#显示当前环境信息poetryenvinfo#列出与项目关联的环境(一个项目可能需要不同版本依赖做测试)poetryenvlist#列出当前配置poetryconfig--list导出requirements.txt文件暂时只支持requirements.txt格式#导出requirements.txt文件-f导出格式--output导出文件名poetryexport-frequirements.txt--outputrequirements.txt