fmod ALLOPS2JSON is
  inc TEMPLATES .    --- lib-util
  inc MY-META-ALL .  --- lib-meta

***(
{
...
 sortName:  {
    "lesser": [ subsortlist ],
    "elements": [ elementlist ],
		"greater": [ supsersortlist ],
 },
 ...
}

)

var mod : Module .
var modname : Qid .

var q : Qid .
var ql : QidList .
vars s s0 : Sort .
vars ss ss0 lss gss : SortSet .
vars str str1 sortspecs subsortstr greaterstr eltstr : String .
var bindings : TBinds .

  op sortsJTemplate : -> String .
  eq sortsJTemplate = "{\n %sortentries \n}" . 

  op sortEntryTemplate : -> String .
	eq sortEntryTemplate = 
"\"%sort\":{\n\
 \t\"lesser\":[%subsortstr],\n\
 \t\"greater\":[%supersortstr],\n\
 \t\"elements\":[%eltstr]}" .
	
	op greaterSorts : Module SortSet Sort SortSet ~> SortSet .
	eq greaterSorts(mod,none,s,ss) = ss .
	eq greaterSorts(mod,s0 ; ss0,s,ss) = 
		   greaterSorts(mod,ss0,s,
	       ss ; (if (s == s0) 
					     then none 
							 else (if sortLeq(mod,s,s0) then s0 else none fi) fi)) . 

	op sorts2json : Qid ~> String .
  ceq sorts2json(modname) =
	       fillTemplate(sortsJTemplate, ("%sortentries" :~ sortspecs)) 
	if mod := upModule(modname,true)
	/\ ss := upSorts(modname,true)
	/\ sortspecs := sorts2jsonX(mod,ss,ss,"") .

	op sorts2jsonX : Module SortSet SortSet String ~> String .
  eq sorts2jsonX(mod,ss0,none,str) = str .
  ceq sorts2jsonX(mod,ss0, s ; ss,str) = sorts2jsonX(mod,ss0, ss,str1)
  if lss :=  lesserSorts(mod, s)
  /\ subsortstr := sortset2cstr(lss,"")
	/\ eltstr :=  qidl2cstr(constListBySort(mod,s),"")
	/\ gss := greaterSorts(mod,ss0,s,none)
	/\ greaterstr := sortset2cstr(gss,"")
	/\ bindings :=	
	    (("%sort" :~ string(s)),
     	 ("%subsortstr"  :~ subsortstr),
			 ("%supersortstr" :~ greaterstr),
       ("%eltstr"  :~ eltstr))
	/\ str1 := str + (if str == "" then "" else ",\n" fi) +
	         	 fillTemplate(sortEntryTemplate, bindings) .

  op sortset2cstr : SortSet String -> String .
  eq sortset2cstr(none,str) = str .
  eq sortset2cstr(s ; ss,str) = 
        sortset2cstr(ss,str 
				  + (if str == "" then "" else ", " fi) 
					+ squote(string(s))) . 
	
  op qidl2cstr : QidList String -> String .
  eq qidl2cstr(nil,str) = str .
  eq qidl2cstr(q ql,str) = 
        qidl2cstr(ql,str 
				  + (if str == "" then "" else ", " fi) 
					+ squote(string(q))) . 

endfm	
