2%:- use_module(library(logicmoo_clif)).
    3%:- use_module(library(logicmoo/typesystem/mpred_type_constraints)).
    4
    5:- use_module(library(logicmoo/dcg_meta)).    6:- use_module(library(logicmoo/util_bb_frame)).    7
    8:- ensure_loaded(library(cgp_lib/cgp_swipl)).    9:- ensure_loaded(library(pfc_lib)).   10
   11:- multifile_data(cg_test_data/2). 
   12%:- multifile_data(skip_cg_test_data/2). 
   13:- multifile_data(id_cg/2).   14
   15%:- current_op(X,Y,'->'),push_operators([op(X,Y,'<-')]).
   16
   17debug_fvar(N,_):- (\+ ground(N) ; number(N)),!.
   18
   19debug_fvar(N,V):- debug_var(N,V).
   20
   21cg_new(CG):- must(push_frame_info([], CG)),!.
   22push_frame_info(Info,Frame):- atom(Frame),must(nb_current_no_nil(Frame,CG)),!,push_frame_info(Info,CG).
   23push_frame_info(Info,Frame):- push_frame(Info,Frame).
   24push_frame_info(Info,Frame,S,S):-push_frame_info(Info,Frame).
   25
   26push_frame_concept(C,Frame):-atom(Frame),must(nb_current_no_nil(Frame,CG)),!,push_frame_concept(C,CG).
   27push_frame_concept(C,Frame):-nop(push_frame(C,Frame)).
   28push_frame_concept(C,Frame,S,S):-push_frame_concept(C,Frame).
   29
   30nb_set_add(X,Y,S,S):- must(nb_set_add(X,Y)).
   31
   32
   33load_cg_test_data:- cg_reader_test_data:ensure_loaded(library('../test/cgp_lib/cg_reader_test_data.plt')).
   34
   35get_cg_test_data(T,D):- load_cg_test_data, cg_test_data(T,D).
   36get_cg_test_data(T,D):- cg_reader_test_data:cg_test_data(T,D).
   37cg_demo :- make,
   38  forall((get_cg_test_data(TstAtts,X), \+ memberchk(failing,TstAtts)),must(do_cg_test(TstAtts,X))).
   39
   40cg_reader_tests :- make,
   41   forall(get_cg_test_data(TstAtts,X), must(do_cg_test(TstAtts,X))).
   42
   43do_cg_test( TstAtts,_):- memberchk(skip,TstAtts),!.
   44do_cg_test( TstAtts,X):- select(cg_dialect(What),TstAtts,NewTstAtts),!, 
   45  locally_setval(cg_dialect,What,do_cg_test( NewTstAtts,X)).
   46do_cg_test( TstAtts,X):- memberchk(xcall,TstAtts),!, 
   47                         must(ignore(call_cg(cg_text(X)))).
   48
   49do_cg_test(_TstAtts,X):- must(ignore(assert_cg(cg_text(X)))), 
   50                         must(ignore(call_cg(cg_text(X)))).
   51
   52subset_loose(S1,S2):- \+ is_list(S2),!,member(S2,S1),!.
   53subset_loose(S1,S2):- subset(S1,S2).
   54
   55cg_test_data(TstAtts,X):- nonvar(TstAtts), var(X), !,
   56  forall((cg_test_data(WasTstAtts,X),subset_loose(WasTstAtts,TstAtts)),
   57     do_cg_test( WasTstAtts,X)).
   58cg_test_data(TstAtts,X):- nonvar(TstAtts), nonvar(X), !, 
   59   exclude(=(skip),TstAtts,NTstAtts),
   60   do_cg_test(NTstAtts,X).
   61
   62
   63%assert_cg(X):- nb_current_no_nil(named_graph,ID),!,pred_cg(assert_cg_real,X),!.
   64assert_cg(X):- newId(Id),!,locally(nb_setval(named_graph,anonymous(Id)), pred_cg(assert_cg_real,X)),!.
   65
   66assert_cg_real_now(named_graph(Id,X)):- !, assert_cg_real_now(Id,X).
   67assert_cg_real_now(X):- nb_current_no_nil(named_graph,Id),  assert_cg_real_now(Id,X).
   68
   69assert_cg_real_now(anonymous(_),[named_graph(Id,X)]):- nonvar(Id), !, assert_cg_real_now(Id,X).
   70%assert_cg_real_now(anonymous(Id),X):- nonvar(Id), !, assert_cg_real_now(Id,X).
   71assert_cg_real_now(Id,X):- frmprint(named_graph(Id, X)), ain(id_cg(Id,X)).
   72
   73assert_cg_real(X):- assert_cg_real_now(X),!.
   74assert_cg_real(X):- is_list(X),list_to_conjuncts(X,J),!,wdmsg(J).
   75
   76
   77
   78call_cg(X):- pred_cg(call_cg_real,X).
   79call_cg_real(X):- frmprint(call_cg(X)),!.
   80call_cg_real(X):- is_list(X),list_to_conjuncts(X,J),!,wdmsg(J).
   81
   82
   83locally_setval(A,B,C,S,E):- locally_setval(A,B,phrase(C,S,E)).
   84
   85sub_compound_term(C,T):- sub_term(E,T),compound(E),E=C.
   86
   87cg_resolved_names(CG0,CG):-
   88   CGT = cg_name(V,N),
   89   sub_compound_term(CGT,CG0),
   90   subst(CG0,CGT,true,CG1),
   91   subst(CG1,V,N,CG2),
   92   CG1\==CG2,!,
   93   cg_resolved_names(CG2,CG).
   94
   95cg_resolved_names(CG0,CG):- 
   96   sub_compound_term(cg_holds(P,_,V),CG0),
   97   (P==attr;P=='Attr';P==isA),
   98   CGT = cg_type(VV,Color),
   99   sub_compound_term(CGT,CG0),
  100   VV==V,
  101   subst(CG0,CGT,true,CG1),
  102   subst(CG1,V,Color,CG2),   
  103   CG1\==CG2,!,
  104   cg_resolved_names(CG2,CG).
  105cg_resolved_names(CG,CG).
  106   
  107
  108parse_toks_cg(Toks,CG):-parse_ncg(CG0,Toks,[]),
  109  cleanup_cg(CG0,CG).
  110
  111cleanup_cg(CG0,CG):- cg_resolved_names(CG0,CG1),remove_trues(CG1,CG).
  112
  113remove_trues(CG1,CG):- sub_compound_term([H|T],CG1),is_list([H|T]),select(true,[H|T],WOT),
  114  subst(CG1,[H|T],WOT,CG2),remove_trues(CG2,CG).
  115remove_trues(CG,CG).
  116
  117pred_cg(Pred, Error):- var(Error),!, trace_or_throw(pred_cg(Pred, Error)).
  118pred_cg(Pred, X):- string(X),!,pred_cg(Pred, cg_text(X)).
  119pred_cg(Pred, [Int|Codes]):- notrace(catch(text_to_string([Int|Codes],X),_,fail)),pred_cg(Pred, cg_text(X)).
  120pred_cg(Pred, X):- is_list(X), !, maplist(pred_cg(Pred),X).
  121pred_cg(Pred, cg_text(A)):- any_to_string(A,X),
  122 locally_setval(cg_text,X,(( 
  123  format('~N~n~n```~n% ===========================================~n% ?- pred_cg(~q,"~w").~n% ===========================================~n~n',[Pred,X]),
  124  ignore((cg_df_to_term(X,Y),ignore((nb_current_no_nil(named_graph,Id), ain(cg_text(Id,X)))), !, pred_cg(Pred, Y))), 
  125  format("~N```~n",[])))),!.
  126
  127
  128pred_cg(Pred, tOkS(Toks)):- !, (parse_toks_cg(Toks,CG)-> pred_cg(Pred, cg(CG)) ; (format("
  129% Failed Parse
  130?- rtrace( 
  131    ~q  
  132   ). ~n",[pred_cg(Pred, tOkS(Toks))]))).
  133
  134pred_cg(Pred, cg(CG)):- nop(wdmsg(call(Pred,CG))), !, call(Pred,CG).
  135pred_cg(Pred, X):- wdmsg(pred_cg(Pred, X)), fail.
  136%pred_cg(Pred, X):- term_to_cg(X, Y),!, pred_cg(Pred, Y),!.
  137pred_cg(_, _):- !.
  138pred_cg(Pred, Error):- trace_or_throw(pred_cg(Pred, Error)).
  139
  140print_cg(X):- is_list(X),!, maplist(print_cg,X).
  141print_cg(X):- !, frmprint(X).
  142print_cg(X):- nl,wdmsg(display(X)),nl.
  143
  144fixcase_atom(Name,NameR):- atom(Name), upcase_atom(Name,Name), \+ downcase_atom(Name,Name), to_case_break_atoms(Name,Atoms),
  145 maplist(to_titlecase,Atoms,PAtoms),sUbst(PAtoms,'-','_',PSAtoms),atomic_list_concat(PSAtoms,NameR),!.
  146fixcase_atom(Name,Name).
  147
  148:- use_module(library(dcg/basics)).  149
  150end_symbol--> `-`, !, end_symbol.
  151end_symbol-->  [C],!, { \+code_type(C, prolog_identifier_continue) }.
  152end_symbol--> \+ [_].
  153prolog_id_conted([])--> dcg_peek(end_symbol),!.
  154prolog_id_conted([C|T])--> [C], !,prolog_id_conted(T).
  155
  156tokenize_cg_w(HT)--> maybe_to_codes,!,tokenize_cg_w(HT).
  157tokenize_cg_w(HT)--> blank,!,tokenize_cg_w(HT).
  158tokenize_cg_w(Name) --> dcg_peek(`'`),!,single_quoted_string(Str),{atom_codes(Name,Str)}.
  159tokenize_cg_w(String) --> dcg_peek(`"`),!,double_quoted_string(String).
  160tokenize_cg_w(Op)--> {sent_op_chars(Op,Chars)},Chars,!.
  161tokenize_cg_w('?'(UNAME)) --> `?`,!,prolog_id_conted(CL),{ atom_codes(Name, CL)},!,{upcase_atom(Name,UNAME)}.
  162tokenize_cg_w(T)--> dcg_basics:number(T),!.
  163tokenize_cg_w(Name)--> [C], {\+code_type(C, prolog_identifier_continue),atom_codes(Name, [C])},!.
  164tokenize_cg_w(Name)--> prolog_id_conted(CL), !,{atom_codes(NameR, CL),fixcase_atom(NameR,Name)},!.
  165tokenize_cg_w(Name)--> [C],{ atom_codes(Name, [C])},!.
  166
  167tokenize_cg(HT)--> maybe_to_codes,!,tokenize_cg(HT).
  168tokenize_cg(HT)--> dcg_basics:blank,!,tokenize_cg(HT).
  169tokenize_cg([],S,E):- S==[],!,E=[].
  170tokenize_cg([H|T])--> tokenize_cg_w(H),!,tokenize_cg(T).
  171tokenize_cg([])-->[],!.                                             
  172
  173
  174
  175%find_var(V)--> cic('*'), cw(VL),cic(']'),!,{upcase_atom(VL,V)},!.
  176%parse_var_concept(V,typeof(Rel, ?(V)))-->  cic('['), cw(Rel), cic(':'),cic('*'), cw(VL),cic(']'),!,{upcase_atom(VL,V)},!.
  177%parse_var_concept(V,C)-->  cic('['),dcg_beforeSeq(LeftSkipped,find_var(V)), {append(['['|LeftSkipped],[']'],CS), concept(C,CS,[])},!.
  178
  179parse_rel(Logic) -->  cic('('),carg(Rel),
  180  dcg_list_of(carg,Args), cic(')'),!,{fixcase_atom(Rel,RelD),Logic=..[cg_holds,RelD|Args]},!.
  181
  182
  183parse_decl(Type, [cg_type(Arg,RelD),cg_decl(Type,Arg)],Arg) -->  cw(Rel), cic('('), carg(Arg), cic(')'),!,{fixcase_atom(Rel,RelD)},!.
  184
  185
  186
  187carg(W)-->dcg_peek(cic('[')),concept(W),!.
  188carg(W)-->dcg_peek(cic('(')),parse_rel(W),!.
  189%carg(_)-->[CI],{sent_op(CI)},!,{fail}.
  190carg(W) --> cw(W),!.
  191carg(V)-->cvalue(W),{concept_var(V,W)}.
  192
  193
  194dcg_list_of( _,['*']) --> cic('*'), ending(_),!.
  195dcg_list_of(_Cw,[]) --> ending(_),!.
  196dcg_list_of( Cw,[H|Frame]) --> cic('|'), !, {append_term(Cw,H,CwH)}, CwH, dcg_list_of(Cw,Frame).
  197dcg_list_of( Cw,[H|Frame]) --> cic(','), !, {append_term(Cw,H,CwH)}, CwH, dcg_list_of(Cw,Frame).
  198dcg_list_of( Cw,[H|Frame]) --> {append_term(Cw,H,CwH)}, CwH, dcg_list_of(Cw,Frame).
  199
  200ending(R) --> {sent_op_pair(_,R)},dcg_peek(cic(R)),!.
  201ending(_) --> \+[_].
  202
  203
  204push_incr(State,Type,Amount):- (get_attr(State,Type,Prev);Prev=0),New is Amount+ Prev,!, put_attr(State,Type,New).
  205get_incrs(State,Type,Amount):- sent_op_pair(Type,_), get_attr(State,Type,Amount).
  206unbalanced_incr(State):- sent_op_pair_q(S),get_incrs(State,S,V),V>0.
  207can_incr(State,_S):- \+ unbalanced_incr(State), !. % sent_op_pair(S,S), O\==S, get_incrs(State,S,V),V>0.
  208
  209ballance([],_):-!.
  210ballance([H|T],State):- sent_op_pair_q(S),H=S,!,
  211 ((get_incrs(State,S,V),V>0) -> push_incr(State,S,-1);push_incr(State,S,+1)),
  212 ballance(T,State).
  213ballance([H|T],State):- sent_op_pair(S,_), H=S, can_incr(State,S), !, push_incr(State,S,+1),ballance(T,State).
  214ballance([H|T],State):- sent_op_pair(S,E), H=E, can_incr(State,S), !, push_incr(State,S,-1),ballance(T,State).
  215ballance([_|T],State):- ballance(T,State).
  216
  217ballanced(L):- notrace((ballance(L,R),\+ ( get_incrs(R,_,V),V\=0))).
  218
  219dcg_beforeSeq(Skipped,Mid,S,E):-
  220  append(Skipped,MidS,S),ballanced(Skipped), phrase(Mid,MidS,E).
  221
  222maybe_codes_to_tokens(_,_):- !, fail.
  223maybe_codes_to_tokens(S,_):- is_list(S), notrace(catch((atom_codes(_,S),fail),_,true)),!,fail.
  224maybe_codes_to_tokens(S,Toks):- \+ is_list(S),!,any_to_atom(S,Atom),atom_codes(Atom,Codes), maybe_codes_to_tokens(Codes,Toks).
  225maybe_codes_to_tokens(S,Toks):- tokenize_cg(Toks,S,[]),!.
  226
  227
  228named_graph_starter(Name)--> cw(Name), (cic('::');(cic(':'),cic(':'))).
  229
  230
  231cg_clause_connective--> (cic('.');cic(',');cic(':-');cic(';')).
  232
  233maybe_to_codes(S,_):- is_list(S), notrace(catch(atom_codes(_,S),_,fail)),!,fail.
  234maybe_to_codes(S,Codes):- any_to_string(S,Str),atom_codes(Str,Codes),!.
  235
  236% parse_ncg(CG) --> maybe_codes_to_tokens,!,parse_ncg(CG).
  237% parse_ncg(named_graph(Name,PCG)) --> cw(Name), (cic('::');(cic(':'),cic(':'))),parse_ncg(PCG).
  238parse_ncg(CG)--> {var(CG)},!, parse_cg(['.'],CG0), {resolve_frame_constants(CG0,CG)},!,dcgOptional(cic('.')).
  239parse_ncg(CG)--> parse_ncg(CG0),!,{push_frame_info(CG0,CG)}.
  240
  241parse_cg(StopAt,CG) --> parse_cg0(StopAt,CG).
  242
  243parse_cg0(StopAt,CG,S,E) :- var(CG), \+ attvar(CG), !,
  244  cg_new(CG), must( \+ ((var(CG), \+ attvar(CG)))),!,locally_setval(cgframe,CG,parse_cg0(StopAt,CG,S,E)).
  245
  246
  247parse_cg0(_StopAt,CG)--> [':-'], !, parse_cg_list([','],PCG), { merge_simular_graph_vars(CG,PCG), 
  248  push_frame_info(preconds(PCG),CG)}.
  249parse_cg0(StopAt,_) --> ends_cg(StopAt),!.
  250
  251parse_cg0(_StopAt,CG) --> named_graph_starter(Name),
  252  {once(nb_current_no_nil(named_graph,WasName);WasName=[])},
  253   locally_setval(named_graph,Name,parse_cg0((cg_clause_connective),PCG)), 
  254  {WasName==Name-> push_frame_info(PCG,CG);push_frame_info(named_graph(Name,PCG),CG)}.
  255
  256parse_cg0(_StopAt,CG)--> {member(Type,[type,individual])}, cic(Type), !, zalwayz(parse_decl(Type,Expr,_X)), !, zalwayz(cic('Is')),!, 
  257 zalwayz(parse_ncg(CG0)),!, {push_frame_info(CG0,CG),push_frame_info(Expr,CG)},!.
  258parse_cg0(StopAt,CG) --> parse_rel(H), {push_frame_info([H],CG)}, parse_cg0(StopAt,CG).
  259parse_cg0(StopAt,CG) --> concept(S), cont_graph(StopAt,S,S,CG),!,parse_cg0(StopAt,CG).
  260
  261ends_cg(   _   ) --> \+ [_],!.
  262ends_cg(StopAt ) --> StopAt,!.
  263ends_cg(   _   ) --> {sent_op_pair(_,R)},dcg_peek(cic(R)),!.
  264ends_cg(   _   ) --> cic('.'),!.
  265
  266
  267parse_cg_list(StopAt,[] ) --> ends_cg(StopAt),!.
  268parse_cg_list(StopAt,[CG|More])--> parse_cg0(StopAt,CG),parse_cg_list(StopAt,More).
  269
  270s_e(S,E,S,E).
  271
  272cont_graph(_StopAt,_Parent,_Subj,CG) --> [':-'], !, parse_cg_list([','],PCG), { merge_simular_graph_vars(CG,PCG), 
  273  push_frame_info(preconds(PCG),CG)}.
  274
  275cont_graph(StopAt,_,_,_) --> ends_cg(StopAt),!.
  276cont_graph(StopAt,Parent,_Subj,CG) --> cic(','),!,cont_graph(StopAt,Parent,Parent,CG).
  277cont_graph(StopAt,Parent,_Subj,CG) --> cic('-'),dcg_peek(cic('-');cic('<-');cic('->')),!,cont_graph((dcg_peek(\+ cic(',')), StopAt),Parent,Parent,CG).
  278
  279cont_graph(StopAt,Parent,Subj,CG) --> rel_right2(Rel),!,concept(Obj),push_frame_info(cg_holds(Rel,Subj,Obj),CG),cont_graph(StopAt,Parent,Obj,CG).
  280cont_graph(StopAt,Parent,Subj,CG) -->  rel_right(Rel),!,concept(Obj),push_frame_info(cg_holds(Rel,Subj,Obj),CG),cont_graph(StopAt,Parent,Obj,CG).
  281
  282cont_graph(StopAt,Parent,Obj,CG) --> rel_left2(Rel),!,concept(Subj),push_frame_info(cg_holds(Rel,Subj,Obj),CG),cont_graph(StopAt,Parent,Subj,CG).
  283cont_graph(StopAt,Parent,Obj,CG) -->  rel_left(Rel),!,concept(Subj),push_frame_info(cg_holds(Rel,Subj,Obj),CG),cont_graph(StopAt,Parent,Subj,CG).
  284
  285cont_graph(StopAt,_Parent,_Subj,CG) --> parse_cg(StopAt,CG).
  286
  287rel_right(Rel)-->cic('-'),rel(Rel),cic('->').
  288rel_right2(Rel)-->cic('->'),rel(Rel),cic('->').
  289rel_right2(Rel)-->cic('->'),rel(Rel),cic('-').
  290rel_left(Rel)-->cic('<-'),rel(Rel),cic('-').
  291rel_left2(Rel)-->cic('<-'),rel(Rel),cic('<-').
  292
  293rel(C)--> ['('],word_tok_loose(C),[')'].
  294rel(C)--> ['<'],word_tok_loose(C),['>'].
  295rel(C)--> word_tok_loose(C).
  296
  297word_tok_loose(DC)-->[C],{atom(C),C\=='', fixcase_atom(C,DC)}.
  298
  299nonword_tok(X):- atom(X),upcase_atom(X,UC),downcase_atom(X,DC),!,UC==DC. 
  300
  301word_tok('#'(X))--> ['#'],word_tok(X),!.
  302word_tok('#')--> ['#'], !.
  303word_tok('*'(X))--> ['*'],word_tok(X),!.
  304word_tok('*')--> ['*'], !.
  305word_tok(?(Var)) --> [?(Var)],!.
  306word_tok(Value) --> [Value],{number(Value)},!.
  307word_tok(*)--> [*], !.
  308word_tok(?(Var)) --> [?(Var)],!.
  309word_tok(X)--> [X], !, {atom(X), \+ nonword_tok(X)}.
  310
  311quant(X) --> [X], {nonword_tok(X)}.
  312
  313                                                  
  314concept(CG) --> maybe_codes_to_tokens,!,concept(CG).
  315concept(V,S,E):- concept0(C,S,E),concept_var(V,C).
  316
  317% concept0('*')--> [*], !.
  318concept0([?(Var)]) --> [?(Var)],!.
  319% concept(vc(V, C))-->parse_var_concept(V,C),!.
  320
  321concept0(C)-->concept2(C),(([I],{integer(I)})->{nb_set_add(C,'#'(I))};[]).
  322
  323%concept1(C)--> cic('['), dcg_peek([P1,P2]), concept_innerds_3a(P1,P2,C),!.
  324concept2(C)--> cic('['), concept_innerds(C), cic(']'),!.
  325concept2(C)--> word_tok(C),!.
  326
  327concept_var(V,C):- \+ is_list(C),concept_var(V,[C]).
  328concept_var(V,C):- maplist(concept_var(V,C),C).
  329
  330% val(X_Cat, [?('X')])
  331concept_var(V, _Props,      Var  ):- var(Var),!, V=Var.
  332concept_var(_, _Props,       []  ):- !.
  333concept_var(V,  Props,    '#'(N) ):-  atomic(N), member(cg_type(Type),Props),!,atomic_list_concat([Type,'#',N],Val),!,
  334  concept_var(V,  Props,   cg_equal(Val)).
  335concept_var(V, _Props,    '@'(E) ):- !,debug_fvar(E,V), push_frame_info(cg_quantz(E,V),cgframe).
  336%concept_var(V, Props, '$VAR'(N),'$VAR'(N) ):- !.
  337concept_var(V, Props, '$VAR'(N) ):-  !,concept_var(V, Props, '?'(N) ).
  338concept_var(V, Props, 'cg_name'(N) ):-  atom(N), downcase_atom(N,N),!,concept_var(V, Props, '*'(N) ).
  339concept_var(V, _Props,    '?'(N) ):- !, upcase_atom(N,U),debug_fvar(N,V),!,push_frame_info(cg_quantz(e,V),cgframe),!,V='$VAR'(U).
  340concept_var(V, _Props,    '*'(N) ):- !,debug_fvar(N,V),upcase_atom(N,NU),push_frame_info(frame_var(NU,V),cgframe),!.
  341
  342concept_var(V, _Props,        M  ):- atomic(M),!,V=M.
  343
  344%concept_var(V, _Props,   = ):- atomic_list_concat([Type,'_'],M),gensym(M,V),
  345%  push_frame_info(cg_type(V,Type),cgframe),push_frame_info(same_values(V,Value),cgframe).
  346
  347concept_var(V, _Props,    IZA ):- compound(IZA),compound_name_arguments(IZA,I,[Z|A]),compound_name_arguments(IZAOUT,I,[V,Z|A]),!,
  348  push_frame_info(IZAOUT,cgframe),debug_fvar(Z,V).
  349concept_var(_, _Props, _):-!.
  350
  351 
  352cvalue_cont([])--> (cic('.'); ending(_)),!.
  353cvalue_cont([]) --> {sent_op(Op)},dcg_peek(cic(Op)),!.
  354cvalue_cont([H|T]) --> cw(H), cvalue_cont(T).
  355
  356
  357cvalue('GRAPH'(W))--> dcg_peek(cic('[')), zalwayz(parse_ncg(W)).
  358cvalue(=(REL))--> dcg_peek(cic('(')), zalwayz(parse_rel(REL)),!.
  359cvalue(=(X,REL))--> dcg_peek((cw(_),cic('('))), parse_decl(instance,REL,X),!.
  360cvalue(textOf(String))--> [String], {string(String)},!.
  361cvalue('='(W))--> cic('='), cvalue(W).
  362cvalue('^'(W))--> cic('^'), cvalue(W).
  363cvalue('~'(W))--> cic('~'), cvalue(W).
  364cvalue('*'(W))--> cic('*'), cw(W).
  365cvalue('?'(W))--> [?(W)],!.
  366% #?Quotient
  367cvalue('='(W))--> cic('#'), [?(W)], {atomic(W)}.
  368cvalue('#'(W))--> cic('#'), [W].
  369% cvalue(cg_count_min_max(W,W))--> cic('@'), [W], { number(W) },!.
  370cvalue('@'(W))--> cic('@'), cw(W).
  371cvalue(cg_count_min_max(0,0))--> cic('{'),  cic('}'),!.
  372cvalue(TstAtts)--> cic('{'), {TstAtts=['@'(set)]}, dcg_list_of(cic,Atts), cic('}'), !, {into_set(Atts,TstAtts)}.
  373cvalue(cg_name(W))--> cw(H), cvalue_cont(T), {maplist(term_to_unquoted_atom,[H|T],HT),atomic_list_concat(HT,'_',W)}.
  374
  375into_set(['*'],TstAtts):- nb_set_add(TstAtts,cg_count_min_max(1,_)),!.
  376into_set(Atts,TstAtts):- append(List,['*'],Atts),length(List,Count), nb_set_add(TstAtts,cg_count_min_max(Count,_)),nb_set_add(TstAtts,cg_values(List)).
  377into_set(List,TstAtts):- length(List,Count), nb_set_add(TstAtts,cg_count_min_max(Count,_)),nb_set_add(TstAtts,cg_values(List)).
  378
  379
  380term_to_unquoted_atom(Atom,Atom):- atom(Atom),!.
  381term_to_unquoted_atom(Term,Atom):- term_to_atom(Term,Atom).
  382
  383concept_innerds([cg_type(C)|Cont]) --> cw(C),cic(','),!, concept_innerds(Cont).
  384concept_innerds(Cont) -->  cic(':'),!,concept_innerds_cont(Cont).
  385concept_innerds([cg_type(C)|Cont]) --> cw(C), dcgOptional(cic(':')),!,concept_innerds_cont(Cont).
  386concept_innerds(Cont) --> concept_innerds_cont(Cont).
  387
  388concept_innerds_cont([])--> ending(_).
  389concept_innerds_cont(HT) --> cvalue(H), !, concept_innerds_cont(T),{flatten([H,T],HT)}.
  390
  391
  392sent_op_chars(Op,Chars):- sent_op(Op),atom_codes(Op,Chars).
  393
  394% these must be before:
  395sent_op('::'). sent_op(':-'). sent_op('->'). sent_op('<-').
  396% these
  397sent_op('-').  sent_op(':').  
  398% then..
  399sent_op(A):- sent_op_pair(A,_).
  400sent_op(A):- sent_op_pair(_,A).
  401sent_op(A):- sent_op_pair_q(A).
  402sent_op(',').  sent_op(';'). 
  403sent_op('|').
  404sent_op('.').  sent_op('='). sent_op('@').  sent_op('#').
  405sent_op('^').  sent_op('*'). sent_op('~').  sent_op('$').
  406
  407sent_op --> [C],{sent_op(C)}.
  408
  409sent_op_pair('<','>').
  410sent_op_pair('{','}'). 
  411sent_op_pair('[',']').
  412sent_op_pair('(',')'). 
  413
  414sent_op_pair_q('"'). 
  415sent_op_pair_q('\''). 
  416
  417
  418cw(H,[H|T],T):- notrace(( \+ sent_op(H))).
  419
  420cic(CI)-->[C],{notrace((atom(C),fixcase_atom(C,UC),(CI=UC->true; fixcase_atom(CI,UC))))}.
  421
  422
  423cg_df_to_term(In,Out):- any_to_string(In,Str),
  424  % replace_in_string(['('='{',')'='}'],Str,Str0),
  425  replace_in_string(['\r'='\n'],Str,Str0),
  426  atom_codes(Str0,Codes),!,
  427  must_or_rtrace(tokenize_cg(Toks,Codes,[])),!,
  428  Out = tOkS(Toks).
  429
  430
  431:- set_dcg_meta_reader_options(file_comment_dialect=cg_lf, cg_comment_expr).  432cg_comment_expr(X) --> cspace,!,cg_comment_expr(X).
  433cg_comment_expr('$COMMENT'(Expr,I,CP)) --> comment_expr_5(Expr,I,CP),!.
  434comment_expr_5(T,N,CharPOS) --> `/*`, !, my_lazy_list_location(file(_,_,N,CharPOS)),!, zalwayz(read_string_until_no_esc(S,`*/`)),!,
  435  {text_to_string_safe(S,T)},!.
  436comment_expr_5(T,N,CharPOS) -->  {cg_cmt_until_eoln(Text)},Text,!, my_lazy_list_location(file(_,_,N,CharPOS)),!,zalwayz(read_string_until_no_esc(S,eoln)),!,
  437 {text_to_string_safe(S,T)},!.
  438cg_cmt_until_eoln(`//`).
  439cg_cmt_until_eoln(`;;`).
  440cg_cmt_until_eoln(`%`).
  441
  442
  443  
  444%:- pop_operators.
  445
  446%:- ensure_loaded(library(cgprolog_inline_reader)).
  447      
  448:- fixup_exports.