Advertisement
aporokizzu

Yaml.ahk (2/3)

Mar 2nd, 2023
915
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Autohotkey 22.15 KB | Source Code | 0 0
  1. ;Yaml v1.0.14 requires AutoHotkey(H) v2.beta+
  2. Yaml(TextFileObject,Yaml:=0,Space:=""){
  3.   If IsObject(TextFileObject)
  4.     return Dump(TextFileObject,Yaml,Space) ; dump object to yaml string
  5.   else If FileExist(TextFileObject)
  6.     return Load(FileRead(TextFileObject),Yaml) ; load yaml from file
  7.   else return Load(TextFileObject,Yaml) ; load object from yaml string
  8.   ;~ G(p,ByRef LF:=""){ ; get line and advance pointer to next line
  9.     ;~ return !p||!NumGet(p,"UShort")?0:(str:=StrSplit(StrGet(P),"`n","`r",2)).Length?(p+=StrLen(LF:=str[1])*2,p+=!NumGet(p,"UShort") ? 0 : NumGet(p,"USHORT")=13?4:2):0
  10.   ;~ }
  11.   Load(txt,Y:=0){ ; convert yaml to object
  12.     local NewDoc:=0,_:="",_C:="",_CE:="",_S:="",V:="",_L:="",O:="",VQ:="",h:="",VC:=""
  13.     static _fun_:=A_PtrSize=8?"SIXJdExED7cBZkWFwHUM60BIg8ECZkWFwHQkZkGD+Ap0IWZBg/gNRA+3QQJ142ZBg/gKdB9Ig8ECZkWFwHXjSInIw4XSdAUx0maJEUiNQQLDMcDDhdJ0BTHAZokBSI1BBMOQkJCQ":"i0QkBIXAdEsPtxBmhdJ1CutBg8ACZoXSdDdmg/oKdCBmg/oND7dQAnXoZoP6CnQmg8ACZoXSdejzw422AAAAAItMJAiFyXQFMdJmiRCDwALD88MxwMOLTCQIhcl0BTHSZokQg8AEw5A=",_sz_,NXTLN,_op_,__:=(DllCall("crypt32\CryptStringToBinary","str",_fun_,"uint",0,"uint",1,"ptr",0,"uint*",&_sz_:=0,"ptr",0,"ptr",0),NXTLN:=DllCall("GlobalAlloc","uint",0,"ptr",_sz_,"ptr"),DllCall("VirtualProtect","ptr",NXTLN,"ptr",_sz_,"uint",0x40,"uint*",&_op_:=0),DllCall("crypt32\CryptStringToBinary","str",_fun_,"uint",0,"uint",1,"ptr",NXTLN,"uint*",&_sz_,"ptr",0,"ptr",0))
  14.     if txt=""
  15.       return []
  16.     else If InStr("[{", SubStr(D:=LTrim(txt," `t`n`r"),1,1))
  17.       return JSONString(D,Yaml) ; create pure json object (different syntax to YAML and better performance)
  18.     pText:=Buffer(StrLen(txt)*2+8,0),StrPut(txt,pText.Ptr)
  19.     P:=pText.Ptr,A:=Map(),D:=[],I:=[]
  20.     Loop 1000
  21.       D.Push(0),I.Push(0)
  22.     ;~ While P:=G(LP:=P,LF){
  23.     While P && (LP:=P,P:=DllCall(NXTLN,"PTR",P,"Int",true,"PTR"),LF:=StrGet(LP),P){ ;P:=(LP:=P,!p||!NumGet(p,"UShort")?0:(str:=StrSplit(StrGet(P),"`n","`r",2)).Length?(p+=StrLen(LF:=str[1])*2,p+=!NumGet(p,"UShort") ? 0 : NumGet(p,"USHORT")=13?4:2):0){
  24.       if (InStr(LF,"---")=1&&!Y)||(InStr(LF,"---")=1&&(Y.Push(""),NEWDOC:=0,D[1]:=0,_L:=_LL:=O:=_Q:=_K:=_S:=_T:=_V:="",1))||(InStr(LF,"...")=1&&NEWDOC:=1)||(LF="")||RegExMatch(LF,"^\s+$")
  25.         continue
  26.       else if NEWDOC
  27.         throw ValueError("Document ended but new document not specified.", 0, LF)
  28.       if RegExMatch(LF,"^\s*#")||InStr(LF,"``%")=1 ; Comments, tag, document start/end or empty line, ignore
  29.         continue
  30.       else If _C || (_S && RegExMatch(StrReplace(LF,A_Tab,"  "),"^\s{" (LL-1) "}")) || (V&&!(K&&Q) && RegExMatch(StrReplace(LF,A_Tab,"  "),"^\s{" LL "}")){ ; Continuing line incl. scalars
  31.         if _Q&&!_K{ ; Sequence
  32.           If D[L].Length && IsObject(VC:=D[L].Pop())
  33.             throw ValueError("Malformed inline YAML string") ; Error if previous value is an object
  34.           else D[L].Push(VC (VC?(_S=">"?" ":"`n"):(LL:=StrLen(StrReplace(SubStr(LF,1,RegexMatch(LF,"[^\s]")-1),A_Tab,"  "))+1,"")) _CE:=SubStr(LF,SCAPrefix(&LF,LL-1))) ; append value to previous item
  35.         } else if IsObject(VC:=D[L][K])
  36.           throw ValueError("Malformed inline YAML string") ; Error if previous value is an object
  37.         else D[L][K]:=VC (VC?(_S=">"?" ":"`n"):(LL:=StrLen(repl:=StrReplace(sub:=SubStr(LF,1,regex:=RegexMatch(LF,"[^\s]")-1),A_Tab,"  "))+1,"")) _CE:=SubStr(LF,SCAPrefix(&LF,LL-1)) ; append value to previous item
  38.           continue
  39.       } else if _C&&(SubStr(_CE,-1)!=_C)
  40.         throw ValueError("Unexpected character", 0, (_Q?D[L][D[L].Length]:D[L][K])) ; else check if quoted value was ended with a quote
  41.       else _C:="" ; reset continuation
  42.       If (CM:=InStr(LF," #"))&&!RegExMatch(LF,".*[`"'].*\s\#.*[`"'].*") ; check for comments and remove
  43.         LF:=SubStr(LF,1,CM-1)
  44.       ; Split line into yaml elements
  45.       If SubStr(LTrim(LF," `t"),1,1)=":"
  46.         throw ValueError("Unexpected character.", 0, ':')
  47.       RegExMatch(LF,"S)^(?<LVL>\s+)?(?<SEQ>-\s)?(?<KEY>`".*`"\s*:\s?|'.*'\s*:\s?|[^:`"'\{\[]+\s*:\s?)?\s*(?<SCA>[\|\>][+-]?)?\s*(?<TYP>!!\w+)?\s*(?<AGET>\*[^\s\t]+)?\s*(?<ASET>&[^\s\t]+)?\s*(?<VAL>`".+`"|'.+'|.+)?\s*$",&_),L:=LL:=StrLen(StrReplace(_.LVL,A_Tab,"  "))+1,Q:=_.SEQ,K:=_.KEY,S:=_.SCA,T:=SubStr(_.TYP,3),V:=UnQuote(_.VAL),V:= IsInteger(V)&&"" V+0=V?V+0:V,VQ:=InStr(".''.`"`".", "." SubStr(LTrim(_.VAL," `t"),1,1) SubStr(RTrim(_.VAL," `t"),-1) ".")
  48.      if L>1{
  49.        if LL=_LL
  50.          L:=_L
  51.        else if LL>_LL
  52.          I[LL]:=L:=_L+1
  53.        else if LL<_LL
  54.          if !I[LL]
  55.            throw ValueError("Indentation problem.", 0, LF)
  56.          else L:=I[LL]
  57.      }
  58.      if Trim(_[]," `t")="-" ; empty sequence not cached by previous line
  59.        V:="",Q:="-"
  60.      else if K=""&&V&&!Q ; only a value is catched, convert to key
  61.        K:=V,V:=""
  62.      If !Q&&SubStr(RTrim(K," `t"),-1)!=":" ; not a sequence and key is missing :
  63.        if L>_L&&(D[_L][_K]:=K,L:=_L,K:=_K,Q:=_Q,_S:=">")
  64.          continue
  65.        else throw ValueError("Invalid key.", 0, LF)
  66.      else if K!="" ; trim key if not empty
  67.        K:=UnQuote(RTrim(K,": "))
  68.      Loop _L!=""?(_L?_L-L:0):A_Index=1?0:D.Length-1 ; remove objects in deeper levels created before
  69.        D[L+A_Index]:=0,I[L+A_Index]:=0
  70.      if !VQ&&_.VAL!=""&&!InStr("'`"",_C:=SubStr(LTrim(_.VAL," `t"),1,1)) ; check if value started with a quote and was not closed so next line continues
  71.         _C:=""
  72.       if _L!=L && !D[L] ; object in this level not created yet
  73.         if L=1{ ; first level, use or create main object
  74.           if Y&&Type(Y[Y.Length])!="String"&&((Q&&Type(Y[Y.Length])!="Array")||(!Q&&Type(Y[Y.Length])="Array"))
  75.             throw ValueError("Mapping Item and Sequence cannot be defined on the same level.", 0, LF) ; trying to create sequence on the same level as key or vice versa
  76.           else D[L]:=Y ? (Type(Y[Y.Length])="String"?(Y[Y.Length]:=Q?[]:Map()):Y[Y.Length]) : (Y:=Q?[[]]:[Map()])[1]
  77.         } else if !_Q&&Type(D[L-1][_K])=(Q?"Array":"Object") ; use previous object
  78.           D[L]:=D[L-1][_K]
  79.         else D[L]:=O:=Q?[]:Map(),_A?A[_A]:=O:"",_Q ? D[L-1].Push(O) : D[L-1][_K]:=O,O:="" ; create new object
  80.       _A:="" ; reset alias
  81.       if Q&&K ; Sequence containing a key, create object
  82.         D[L].Push(O:=Map()),D[++L]:=O,Q:=O:="",LL+=StrLen(StrReplace(_.SEQ,A_Tab,"  ")),I[LL]:=L
  83.       If (Q&&Type(D[L])!="Array"||!Q&&Type(D[L])="Array")
  84.         throw ValueError("Mapping Item and Sequence cannot be defined on the same level,", 0, LF) ; trying to create sequence on the same level as key or vice versa
  85.       if T="binary"{ ; !!binary
  86.         O:=Buffer(StrLen(V)//2),PBIN:=O.Ptr
  87.         Loop Parse V
  88.           If (""!=h.=A_LoopField) && !Mod(A_Index,2)
  89.             NumPut("UChar","0x" h,PBIN,A_Index/2-1),h:=""
  90.       } else if T="set"
  91.         throw ValueError("Tag 'set' is not supported") ; tag !!set is not supported
  92.       else V:=T="int"||T="float"?V+0:T="str"?V "":T="null"?"":T="bool"?(V="true"?true:V="false"?false:V):V ; tags !!int !!float !!str !!null !!bool - else seq map omap ignored
  93.       if _.ASET
  94.         A[_A:=SubStr(_.ASET,2)]:=V
  95.       if _.AGET
  96.         V:=A[SubStr(_.AGET,2)]
  97.       else If !VQ && SubStr(LTrim(V," `t"),1,1)="{" ; create json map object
  98.         O:=Map(),_A?A[_A]:=O:"",P:=(JSONMap(O,LP+InStr(LF,V)*2,L))
  99.       else if !VQ && SubStr(LTrim(V," `t"),1,1)="[" ; create json sequence object
  100.         O:=[],_A?A[_A]:=O:"",P:=(JSONArray(O,LP+InStr(LF,V)*2,L))
  101.       if Q ; push sequence value into an object
  102.         (V ? D[L].Push(O?O:S?"":V) : 0)
  103.       else D[L][K]:=O?O:D[L].HasOwnProp(K)?D[L][K]:S?"":V ; add key: value into object
  104.       if !Q&&V ; backup yaml elements
  105.         _L:=L,_LL:=LL,O:=_Q:=_K:=_S:=_T:=_V:="" ;_L:=
  106.       else _L:=L,_LL:=LL,_Q:=Q,_K:=K,_S:=S,_T:=T,_V:=V,O:=""
  107.     }
  108.     if Y&&Type(Y[Y.Length])="String"
  109.       Y.Pop()
  110.     return Y
  111.   }
  112.   SCAPrefix(&LF,LL){
  113.     Loop Parse, LF
  114.       if !LL-=A_LoopField=A_Tab?2:1
  115.         return A_Index+1
  116.   }
  117.   UniChar(S,e:=1){ ; UniChar: convert unicode and special characters
  118.     local v:=""
  119.     static m:=Map(Ord('"'),'"',Ord("a"),"`a",Ord("b"),"`b",Ord("t"),"`t",Ord("n"),"`n",Ord("v"),"`v",Ord("f"),"`f",Ord("r"),"`r",Ord("e"),Chr(0x1B),Ord("N"),Chr(0x85),Ord("P"),Chr(0x2029),0,"",Ord("L"),Chr(0x2028),Ord("_"),Chr(0xA0))
  120.     Loop Parse S,"\"
  121.       If !((e:=!e)&&A_LoopField=""?v.="\":!e?(v.=A_LoopField,1):0)
  122.         v .= (t:=InStr("ux",SubStr(A_LoopField,1,1)) ? SubStr(A_LoopField,1,RegExMatch(A_LoopField,"^[ux]?([\dA-F]{4})?([\dA-F]{2})?\K")-1) : "")&&RegexMatch(t,"i)^[ux][\da-f]+$") ? Chr(Abs("0x" SubStr(t,2))) SubStr(A_LoopField,RegExMatch(A_LoopField,"^[ux]?([\dA-F]{4})?([\dA-F]{2})?\K")) : m.has(Ord(A_LoopField)) ? m[Ord(A_LoopField)] SubStr(A_LoopField,2) : "\" A_LoopField,e:=A_LoopField=""?e:!e
  123.     return v
  124.   }
  125.   CharUni(&S){ ; CharUni: convert text to unicode notation
  126.     local v:=""
  127.     static ascii:=Map("\","\","`a","a","`b","b","`t","t","`n","n","`v","v","`f","f","`r","r",Chr(0x1B),"e","`"","`"",Chr(0x85),"N",Chr(0x2029),"P",Chr(0x2028),"L","","0",Chr(0xA0),"_")
  128.     If !RegexMatch(s,"[\X{007F}-\X{FFFF}]"){ ;!(v:="") &&
  129.       Loop Parse, S
  130.         v .= ascii.Has(A_LoopField) ? "\" ascii[A_LoopField] : A_LoopField
  131.       return v
  132.     }
  133.     Loop Parse, S
  134.       v .= ascii.Has(A_LoopField) ? "\" ascii[A_LoopField] : Ord(A_LoopField)<128 ? A_LoopField : "\u" format("{1:.4X}",Ord(A_LoopField))
  135.     return v
  136.   }
  137.   Quote(S, J:=1){ ; EscIfNeed: check if escaping needed and convert to unicode notation
  138.     If S=""
  139.       return '""'
  140.     else if (J<1&&!InStr("IntegerFloat",Type(S)))||RegExMatch(S,"m)[\{\[`"'\r\n]|:\s|,\s|\s#")||RegExMatch(S,"^[\s#\\\-:>]")||RegExMatch(S,"m)\s$")||RegExMatch(S,"m)[\X{7F}-\X{7FFF}]")
  141.      return ('"' CharUni(&S) '"')
  142.    else return S
  143.  }
  144.  UnQuote(S){ ; UnQuote: remove quotes
  145.    return (t:=SubStr(S:=Trim(S," `t"),1,1) SubStr(S,-1)) = '""' ? (InStr(S,"\")?UniChar(SubStr(S,2,-1)):SubStr(S,2,-1)) : t = "''" ? SubStr(S,2,-1) : S
  146.  }
  147.  Dump(O:="",J:=0,Space:=""){ ; dump object to string
  148.    local D:=""
  149.    if Type(O)!="Array"||!O.Length||!IsObject(O[1])
  150.      D.= DumpObj(O,J,,,Space)
  151.    else if j<1 {
  152.      for K,V in O
  153.        D.=DumpObj(V,J,,,Space) (j<0?"`n,":",")
  154.      return J<0?"[`n  " StrReplace(RTrim(D,",`n"),"`n","`n  ") "`n]":"[" RTrim(D,",`n") "]"
  155.    } else
  156.      for K,V in O
  157.        D.="---`n" DumpObj(V,J,,,Space) "`n"
  158.    return RTrim(D,",`n")
  159.  }
  160.  DumpObj(O:="",J:=0,R:=0,Q:=0,Space:=""){ ; helper: convert object to yaml string
  161.    static M1:="{",M2:="}",S1:="[",S2:="]",N:="`n",C:=",",S:="- ",E:="",K:=":",Indent:="                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  "
  162.    If (t:=type(O))="Array"{
  163.      D:=J<1&&!R?S1:""
  164.      for key, value in O{
  165.        if Type(value)="Buffer"{
  166.          Loop (VAL:="",PTR:=value.Ptr,value.size)
  167.            VAL.=format("{1:.2X}",NumGet(PTR+A_Index-1,"UCHAR"))
  168.          value:="!!binary " VAL,F:=E
  169.        } else
  170.          F:=IsObject(value)?(Type(value)="Array"?"S":"M"):E
  171.         Z:=Type(value)="Array"&&value.Length=0?"[]":((Type(value)="Map"&&value.count=0)||(Type(value)="Object"&&ObjOwnPropCount(value)=0))?"{}":""
  172.        If J<=R
  173.          D.=(J<R*-1?"`n" SubStr(Indent,(R+1)*-2):"") (F?(%F%1 (Z?"":DumpObj(value,J,R+1,F,Space)) %F%2):Space Quote(value, J)) ((Type(O)="Array"&&O.Length=A_Index) ? E : C)
  174.        else if ((D:=D N SubStr(Indent,R*-2) S)||1)&&F
  175.            D.= Z?Z:(J<=(R+1)?%F%1:E) DumpObj(value,J,R+1,F,Space) (J<=(R+1)?%F%2:E)
  176.        else D .= " " Space Quote(value,J)
  177.      }
  178.    } else {
  179.      D:=J<1&&!R?M1:""
  180.      for key, value in Type(O)="Map"?(Y:=1,O):(Y:=0,O.OwnProps()){
  181.        if Type(value)="Buffer"{
  182.          Loop (VAL:="",PTR:=value.Ptr,value.size)
  183.            VAL.=format("{1:.2X}",NumGet(PTR+A_Index-1,"UCHAR"))
  184.          value:="!!binary " VAL,F:=E
  185.        } else
  186.          F:=IsObject(value)?(Type(value)="Array"?"S":"M"):E
  187.         Z:=Type(value)="Array"&&value.Length=0?"[]":((Type(value)="Map"&&value.count=0)||(Type(value)="Object"&&ObjOwnPropCount(value)=0))?"{}":""
  188.        If J<=R
  189.          D.=(J<R*-1?"`n" SubStr(Indent,(R+1)*-2):"") (Q="S"&&A_Index=1?M1:E) Quote(key,J) Space K (F?(%F%1 (Z?"":DumpObj(value,J,R+1,F,Space)) %F%2):Space Quote(value,J)) (Q="S"&&A_Index=(Y?O.count:ObjOwnPropCount(O))?M2:E) (J!=0||R?(A_Index=(Y?O.count:ObjOwnPropCount(O))?E:C):E)
  190.        else If ((D:=D N SubStr(Indent,R*-2) Quote(key,J) Space K)||1)&&F
  191.          D.= Z?Z:(J<=(R+1)?%F%1:E) DumpObj(value,J,R+1,F,Space) (J<=(R+1)?%F%2:E)
  192.        else D .= " " Space Quote(value, J)
  193.        If J=0&&!R
  194.          D.= (A_Index<(Y?O.count:ObjOwnPropCount(O))?C:E)
  195.      }
  196.    }
  197.     if J<0&&J<R*-1
  198.       D.= "`n" SubStr(Indent,R*-2)
  199.    If R=0
  200.      D:=RegExReplace(D,"^\R+") (J<1?(Type(O)="Array"?S2:M2):"")
  201.    Return D
  202.  }
  203.  JSONMap(O,P,L){ ; YamlObject: convert json map
  204.    static _fun_:=A_PtrSize=8?"SIXJdExED7cBZkWFwHUM60BIg8ECZkWFwHQkZkGD+Ap0IWZBg/gNRA+3QQJ142ZBg/gKdB9Ig8ECZkWFwHXjSInIw4XSdAUx0maJEUiNQQLDMcDDhdJ0BTHAZokBSI1BBMOQkJCQ":"i0QkBIXAdEsPtxBmhdJ1CutBg8ACZoXSdDdmg/oKdCBmg/oND7dQAnXoZoP6CnQmg8ACZoXSdejzw422AAAAAItMJAiFyXQFMdJmiRCDwALD88MxwMOLTCQIhcl0BTHSZokQg8AEw5A=",_sz_,NXTLN,_op_,__:=(DllCall("crypt32\CryptStringToBinary","str",_fun_,"uint",0,"uint",1,"ptr",0,"uint*",&_sz_:=0,"ptr",0,"ptr",0),NXTLN:=DllCall("GlobalAlloc","uint",0,"ptr",_sz_,"ptr"),DllCall("VirtualProtect","ptr",NXTLN,"ptr",_sz_,"uint",0x40,"uint*",&_op_:=0),DllCall("crypt32\CryptStringToBinary","str",_fun_,"uint",0,"uint",1,"ptr",NXTLN,"uint*",&_sz_,"ptr",0,"ptr",0))
  205.    v:=q:=k:=0,key:=val:=lf:=nl:=""
  206.    If ""!=c:=Chr(NumGet(p,"UShort"))
  207.    Loop {
  208.      if c="`n"||(c="`r"&&10=NumGet(p+2,"UShort")){
  209.        if (q||k||(!v&&!k)||SubStr(Ltrim(StrGet(p+(c="`n"?2:4))," `t`r`n"),1,1)="}") && P+=c="`n"?2:4
  210.          continue
  211.        else throw ValueError("Malformed inline YAML string", 0, StrGet(p-6))
  212.      } else if !q&&(c=" "||c=A_Tab) && P+=2
  213.        continue
  214.      else if !v&&(c='"'||c="'") && (q:=c,v:=1,P+=2)
  215.         continue
  216.       else if !v&&k&&(c="["||c="{") && (P:=c="[" ? JSONArray(O[key]:=[],P+2,L) : JSONMap(O[key]:=Map(),P+2,L),key:="",k:=0,1)
  217.         continue
  218.       else if v&&!k&&((!q&&c=":")||(q&&q=c)) && (v:=0,key:=!q && IsNumber(key)&&"" key+0=key?key+0:q?(InStr(key,"\")?UniChar(key):key):Trim(key," `t"),k:=1,q:=0,P+=2)
  219.         continue
  220.       else if v&&k&&((!q&&c=",")||(q&&q=c)) && (v:=0,O[key]:=!q && IsNumber(val)&&"" val+0=val ? val+0 : q ? (InStr(val,"\")?UniChar(val):val) : Trim(val," `t"),val:="",key:="",q:=0,k:=0,P+=2)
  221.         continue
  222.       else if !q&&c="}"&&(k&&v?(O[key]:=val,1):1){
  223.         ;~ if ((tp:=G(P+2,lf))&&(NumGet(P+2,"UShort")=10||NumGet(P+4,"UShort")=10||(nl:=RegExMatch(lf,"^\s+?$"))||RegExMatch(lf,"^\s*[,\}\]]")))
  224.         if ((tp:=DllCall(NXTLN,"PTR",P+2,"Int",false,"PTR"),lf:=StrGet(P+2),tp)&&(NumGet(P+2,"UShort")=0||(nl:=RegExMatch(lf,"^\s+?$"))||RegExMatch(lf,"^\s*[,\}\]]")))
  225.           return nl?DllCall(NXTLN,"PTR",P+2,"Int",true,"PTR"):lf?P+2:NumGet(P+4,"UShort")=0?P+6:P+4 ; in case `r`n we have 2 times NULL chr
  226.         else if !tp
  227.           return NumGet(P+4,"UShort")=0?P+6:P+4 ; in case `r`n we have 2 times NULL chr
  228.         else throw ValueError("Malformed inline YAML string.", 0, StrGet(p))
  229.       } else if !v&&(c=","||c=":"||c=" "||c="`t")&&P+=2
  230.         continue
  231.       else if !v&& (!k ? (key:=c) : val:=c,v:=1,P+=2)
  232.         continue
  233.       else if v&& (!k ? (key.=c) : val.=c,P+=2)
  234.         continue
  235.       else throw ValueError("Undefined")
  236.     } Until(""=c:=Chr(NumGet(p,"UShort")))
  237.     return P
  238.   }
  239.   JSONArray(O,P,L){ ; YamlArray: convert json sequence
  240.     static s:="",_fun_:=A_PtrSize=8?"SIXJdExED7cBZkWFwHUM60BIg8ECZkWFwHQkZkGD+Ap0IWZBg/gNRA+3QQJ142ZBg/gKdB9Ig8ECZkWFwHXjSInIw4XSdAUx0maJEUiNQQLDMcDDhdJ0BTHAZokBSI1BBMOQkJCQ":"i0QkBIXAdEsPtxBmhdJ1CutBg8ACZoXSdDdmg/oKdCBmg/oND7dQAnXoZoP6CnQmg8ACZoXSdejzw422AAAAAItMJAiFyXQFMdJmiRCDwALD88MxwMOLTCQIhcl0BTHSZokQg8AEw5A=",_sz_,NXTLN,_op_,__:=(DllCall("crypt32\CryptStringToBinary","str",_fun_,"uint",0,"uint",1,"ptr",0,"uint*",&_sz_:=0,"ptr",0,"ptr",0),NXTLN:=DllCall("GlobalAlloc","uint",0,"ptr",_sz_,"ptr"),DllCall("VirtualProtect","ptr",NXTLN,"ptr",_sz_,"uint",0x40,"uint*",&_op_:=0),DllCall("crypt32\CryptStringToBinary","str",_fun_,"uint",0,"uint",1,"ptr",NXTLN,"uint*",&_sz_,"ptr",0,"ptr",0))
  241.     v:=q:=c:=tp:=0,lf:=nl:=""
  242.     If ""!=c:=Chr(NumGet(p,"UShort"))
  243.     Loop {
  244.       if c="`n"||(c="`r"&&10=NumGet(p+2,"UShort")){
  245.         if (q||!v||SubStr(Ltrim(StrGet(p+(c="`n"?2:4))," `t`r`n"),1,1)="]") && P+=c="`n"?2:4
  246.           continue
  247.         else throw ValueError("Malformed inline YAML string.", 0, s "`n" StrGet(p-6))
  248.       } else if !q&&(c=" "||c=A_Tab) && P+=2
  249.         continue
  250.       else if !v&&(c='"'||c="'") && (q:=c,v:=1,P+=2)
  251.        continue
  252.      else if !v&&(c="["||c="{") && (P:=c="[" ? JSONArray((O.Push(lf:=[]),lf),P+2,L) : JSONMap((O.Push(lf:=Map()),lf),P+2,L),lf:="",1)
  253.        continue
  254.      else if v&&((!q&&c=",")||(q&&c=q)) && (v:=0,O.Push(!q && IsNumber(lf)&&"" lf+0=lf ? lf+0 : q ? (InStr(lf,"\")?UniChar(lf):lf) : Trim(lf," `t")),q:=0,lf:="",P+=2)
  255.        continue
  256.      else if !q&&c="]"&&(v?(O.Push(Trim(lf," `t")),1):1){
  257.        ;~ if ((tp:=G(P+2,lf))&&(NumGet(P+2,"UShort")=10||NumGet(P+4,"UShort")=10||(nl:=RegExMatch(lf,"^\s+?$"))||RegExMatch(lf,"^\s*[,\}\]]")))
  258.        if ((tp:=DllCall(NXTLN,"PTR",P+2,"Int",false,"PTR"),lf:=StrGet(P+2),tp)&&(NumGet(P+2,"UShort")=0||(nl:=RegExMatch(lf,"^\s+?$"))||RegExMatch(lf,"^\s*[,\}\]]")))
  259.          return nl?DllCall(NXTLN,"PTR",P+2,"Int",true,"PTR"):lf?P+2:NumGet(P+4,"UShort")=0?P+6:P+4 ; in case `r`n we have 2 times NULL chr
  260.        else if !tp
  261.          return NumGet(P+4,"UShort")=0?P+6:P+4 ; in case `r`n we have 2 times NULL chr
  262.        else throw ValueError("Malformed inline YAML string.", 0, StrGet(p))
  263.      } else if !v&&(c=","||c=" "||c="`t")&&P+=2 ;InStr(", `t",c)
  264.        continue
  265.      else if !v&& (lf.=c,v:=1,P+=2)
  266.        continue
  267.      else if v&& (lf.=c,P+=2)
  268.        continue
  269.      else throw ValueError("Undefined")
  270.    } Until(""=c:=Chr(NumGet(p,"UShort")))
  271.    return P
  272.  }
  273.  JSONString(S,Y){ ; PureJSON: convert pure JSON Object
  274.    local NQ:="",LF:="",LP:=0,P:="",R:=""
  275.    D:=[C:=(A:=InStr(S,"[")=1)?[]:Map()],S:=LTrim(SubStr(S,2)," `t`r`n"),L:=1,N:=0,V:=K:="",Y?(Y.Push(C),J:=Y):J:=[C],!(Q:=InStr(S,'"')!=1)?S:=LTrim(S,'"'):""
  276.    Loop Parse, S, '"' {
  277.       Q:=NQ?1:!Q
  278.       NQ:=Q&&(SubStr(A_LoopField,-3)="\\\"||(SubStr(A_LoopField,-1)="\"&&SubStr(A_LoopField,-2)!="\\"))
  279.       if !Q {
  280.         If (t:=Trim(A_LoopField," `t`r`n"))=","||(t=":"&&V:=1)
  281.           continue
  282.         else If t&&(InStr("{[]},:",SubStr(t,1,1)) || RegExMatch(t,"^\d*\s*[,\]\}]")){
  283.           Loop Parse, t {
  284.             if N&&N--
  285.               continue
  286.             If InStr("`n`r `t",A_LoopField)
  287.               continue
  288.             else If InStr("{[",A_LoopField){
  289.               if !A&&!V
  290.                 throw ValueError("Malformed JSON - missing key.",0,t)
  291.               C:=A_LoopField="["?[]:Map(),A?D[L].Push(C):D[L][K]:=C,D.Has(++L)?D[L]:=C:D.Push(C),V:="",A:=Type(C)="Array"
  292.               continue
  293.             } else if InStr("]}",A_LoopField){
  294.               If !A&&V
  295.                 throw ValueError("Malformed JSON - missing value.",0, t)
  296.               else if L=0
  297.                 throw ValueError("Malformed JSON - to many closing brackets.", 0, t)
  298.               else C:=--L=0?"":D[L],A:=Type(C)="Array"
  299.             } else if !(InStr(" `t`r,",A_LoopField)||(A_LoopField=":"&&V:=1)){
  300.               If RegExMatch(SubStr(t,A_Index),"m)^(null|false|true|-?\d+\.?\d*)\s*[,}\]\r\n]",&R)&&(N:=R.Len(0)-2,R:=R.1,1){
  301.                 if A
  302.                   C.Push(R="null"?"":R="true"?true:R="false"?false:"" R+0=R?R+0:R)
  303.                 else if V
  304.                   C[K]:=R="null"?"":R="true"?true:R="false"?false:"" R+0=R?R+0:R,K:=V:=""
  305.                 else throw ValueError("Malformed JSON - missing key.", 0, t)
  306.               } else
  307.                 throw ValueError("Malformed JSON - unrecognized character-", 0, A_LoopField " in " t)
  308.             }
  309.           }
  310.         }
  311.       } else if NQ&&(P.=A_LoopField '"',1)
  312.        continue
  313.      else if A
  314.        LF:=P A_LoopField,C.Push(LF~="^(?!0)-?\d+\.?\d*$"&&"" LF+0=LF?LF+0:InStr(LF,"\")?UniChar(LF):LF),P:=""
  315.      else if V
  316.        LF:=P A_LoopField,C[K]:=LF~="^(?!0)-?\d+\.?\d*$"&&"" LF+0=LF?LF+0:InStr(LF,"\")?UniChar(LF):LF,K:=V:=P:=""
  317.      else
  318.        LF:=P A_LoopField,K:=LF~="^(?!0)-?\d+\.?\d*$"&&"" LF+0=LF?LF+0:InStr(LF,"\")?UniChar(LF):LF,P:=""
  319.    }
  320.    return J[1]
  321.  }
  322. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement