source: git/Singular/iplib.cc @ eebdf2

fieker-DuValspielwiese
Last change on this file since eebdf2 was 43fb497, checked in by Hans Schoenemann <hannes@…>, 7 years ago
code cleanup: sleftv* -> leftv, calling proc. etc.
  • Property mode set to 100644
File size: 33.6 KB
Line 
1/****************************************
2*  Computer Algebra System SINGULAR     *
3****************************************/
4/*
5* ABSTRACT: interpreter: LIB and help
6*/
7
8
9
10
11
12#include <kernel/mod2.h>
13
14#include <Singular/tok.h>
15#include <misc/options.h>
16#include <Singular/ipid.h>
17#include <omalloc/omalloc.h>
18#include <polys/monomials/ring.h>
19#include <Singular/subexpr.h>
20#include <Singular/ipid.h>
21#include <Singular/ipshell.h>
22#include <Singular/fevoices.h>
23#include <Singular/lists.h>
24
25//#include <stdlib.h>
26#include <stdio.h>
27#include <string.h>
28#include <ctype.h>
29#include <sys/stat.h>
30
31
32#if SIZEOF_LONG == 8
33#define SI_MAX_NEST 500
34#elif defined(__CYGWIN__)
35#define SI_MAX_NEST 480
36#else
37#define SI_MAX_NEST 1000
38#endif
39
40#if defined(ix86Mac_darwin) || defined(x86_64Mac_darwin) || defined(ppcMac_darwin)
41#  define MODULE_SUFFIX bundle
42#elif defined(__CYGWIN__)
43#  define MODULE_SUFFIX dll
44#else
45#  define MODULE_SUFFIX so
46#endif
47
48#define MODULE_SUFFIX_STRING EXPANDED_STRINGIFY(MODULE_SUFFIX)
49
50
51#ifdef HAVE_DYNAMIC_LOADING
52BOOLEAN load_modules(const char *newlib, char *fullname, BOOLEAN autoexport);
53#endif
54
55#ifdef HAVE_LIBPARSER
56#  include "libparse.h"
57#else /* HAVE_LIBPARSER */
58procinfo *iiInitSingularProcinfo(procinfov pi, const char *libname,
59              const char *procname, int line, long pos, BOOLEAN pstatic=FALSE);
60#endif /* HAVE_LIBPARSER */
61
62extern int iiArithAddCmd(const char *szName, short nAlias, short nTokval,
63                         short nToktype, short nPos);
64
65#include <Singular/mod_lib.h>
66
67#ifdef HAVE_LIBPARSER
68void yylprestart (FILE *input_file );
69int current_pos(int i=0);
70extern int yylp_errno;
71extern int yylplineno;
72extern char *yylp_errlist[];
73void print_init();
74libstackv library_stack;
75#endif
76
77//int IsCmd(char *n, int tok);
78char mytolower(char c);
79
80/*2
81* return TRUE if the libray libname is already loaded
82*/
83BOOLEAN iiGetLibStatus(char *lib)
84{
85  idhdl hl;
86
87  char *plib = iiConvName(lib);
88  hl = basePack->idroot->get(plib,0);
89  omFree(plib);
90  if((hl==NULL) ||(IDTYP(hl)!=PACKAGE_CMD))
91  {
92    return FALSE;
93  }
94  return (strcmp(lib,IDPACKAGE(hl)->libname)==0);
95}
96
97/*2
98* find the library of an proc:
99*  => return (pi->libname)
100*/
101char * iiGetLibName(procinfov pi)
102{
103  return pi->libname;
104}
105
106/*2
107* given a line 'proc[ ]+{name}[ \t]*'
108* return a pointer to name and set the end of '\0'
109* changes the input!
110* returns: e: pointer to 'end of name'
111*          ct: changed char at the end of s
112*/
113char* iiProcName(char *buf, char & ct, char* &e)
114{
115  char *s=buf+5;
116  while (*s==' ') s++;
117  e=s+1;
118  while ((*e>' ') && (*e!='(')) e++;
119  ct=*e;
120  *e='\0';
121  return s;
122}
123
124/*2
125* given a line with args, return the argstr
126*/
127char * iiProcArgs(char *e,BOOLEAN withParenth)
128{
129  while ((*e==' ') || (*e=='\t') || (*e=='(')) e++;
130  if (*e<' ')
131  {
132    if (withParenth)
133    {
134      // no argument list, allow list #
135      return omStrDup("parameter list #;");
136    }
137    else
138    {
139      // empty list
140      return omStrDup("");
141    }
142  }
143  BOOLEAN in_args;
144  BOOLEAN args_found;
145  char *s;
146  char *argstr=(char *)omAlloc(127); // see ../omalloc/omTables.inc
147  int argstrlen=127;
148  *argstr='\0';
149  int par=0;
150  do
151  {
152    args_found=FALSE;
153    s=e; // set s to the starting point of the arg
154         // and search for the end
155    // skip leading spaces:
156    loop
157    {
158      if ((*s==' ')||(*s=='\t'))
159        s++;
160      else if ((*s=='\n')&&(*(s+1)==' '))
161        s+=2;
162      else // start of new arg or \0 or )
163        break;
164    }
165    e=s;
166    while ((*e!=',')
167    &&((par!=0) || (*e!=')'))
168    &&(*e!='\0'))
169    {
170      if (*e=='(') par++;
171      else if (*e==')') par--;
172      args_found=args_found || (*e>' ');
173      e++;
174    }
175    in_args=(*e==',');
176    if (args_found)
177    {
178      *e='\0';
179      // check for space:
180      if ((int)strlen(argstr)+12 /* parameter + ;*/ +(int)strlen(s)>= argstrlen)
181      {
182        argstrlen*=2;
183        char *a=(char *)omAlloc( argstrlen);
184        strcpy(a,argstr);
185        omFree((ADDRESS)argstr);
186        argstr=a;
187      }
188      // copy the result to argstr
189      if(strncmp(s,"alias ",6)!=0)
190      {
191        strcat(argstr,"parameter ");
192      }
193      strcat(argstr,s);
194      strcat(argstr,"; ");
195      e++; // e was pointing to ','
196    }
197  } while (in_args);
198  return argstr;
199}
200
201/*2
202* locate `procname` in lib `libname` and find the part `part`:
203*  part=0: help, between, but excluding the line "proc ..." and "{...":
204*    => return
205*  part=1: body, between "{ ..." and "}", including the 1. line, w/o "{"
206*    => set pi->data.s.body, return NULL
207*  part=2: example, between, but excluding the line "exapmle {..." and "}":
208*    => return
209*/
210char* iiGetLibProcBuffer(procinfo *pi, int part )
211{
212  char buf[256], *s = NULL, *p;
213  long procbuflen;
214
215  FILE * fp = feFopen( pi->libname, "rb", NULL, TRUE );
216  if (fp==NULL)
217  {
218    return NULL;
219  }
220
221  fseek(fp, pi->data.s.proc_start, SEEK_SET);
222  if(part==0)
223  { // load help string
224    int i, offset=0;
225    long head = pi->data.s.def_end - pi->data.s.proc_start;
226    procbuflen = pi->data.s.help_end - pi->data.s.help_start;
227    if (procbuflen<5)
228    {
229      fclose(fp);
230      return NULL; // help part does not exist
231    }
232    //Print("Help=%ld-%ld=%d\n", pi->data.s.body_start,
233    //    pi->data.s.proc_start, procbuflen);
234    s = (char *)omAlloc(procbuflen+head+3);
235    myfread(s, head, 1, fp);
236    s[head] = '\n';
237    fseek(fp, pi->data.s.help_start, SEEK_SET);
238    myfread(s+head+1, procbuflen, 1, fp);
239    fclose(fp);
240    s[procbuflen+head+1] = '\n';
241    s[procbuflen+head+2] = '\0';
242    offset=0;
243    for(i=0;i<=procbuflen+head+2; i++)
244    {
245      if(s[i]=='\\' &&
246         (s[i+1]=='"' || s[i+1]=='{' || s[i+1]=='}' || s[i+1]=='\\'))
247      {
248        i++;
249        offset++;
250      }
251      if(offset>0) s[i-offset] = s[i];
252    }
253    return(s);
254  }
255  else if(part==1)
256  { // load proc part - must exist
257    procbuflen = pi->data.s.def_end - pi->data.s.proc_start;
258    char *ss=(char *)omAlloc(procbuflen+2);
259    //fgets(buf, sizeof(buf), fp);
260    myfread( ss, procbuflen, 1, fp);
261    char ct;
262    char *e;
263    s=iiProcName(ss,ct,e);
264    char *argstr=NULL;
265    *e=ct;
266    argstr=iiProcArgs(e,TRUE);
267
268    assume(pi->data.s.body_end > pi->data.s.body_start);
269
270    procbuflen = pi->data.s.body_end - pi->data.s.body_start;
271    pi->data.s.body = (char *)omAlloc( strlen(argstr)+procbuflen+15+
272                                      strlen(pi->libname) );
273    //Print("Body=%ld-%ld=%d\n", pi->data.s.body_end,
274    //    pi->data.s.body_start, procbuflen);
275    assume(pi->data.s.body != NULL);
276    fseek(fp, pi->data.s.body_start, SEEK_SET);
277    strcpy(pi->data.s.body,argstr);
278    myfread( pi->data.s.body+strlen(argstr), procbuflen, 1, fp);
279    fclose( fp );
280    procbuflen+=strlen(argstr);
281    omFree(argstr);
282    omFree(ss);
283    pi->data.s.body[procbuflen] = '\0';
284    strcat( pi->data.s.body+procbuflen, "\n;return();\n\n" );
285    strcat( pi->data.s.body+procbuflen+13,pi->libname);
286    s=(char *)strchr(pi->data.s.body,'{');
287    if (s!=NULL) *s=' ';
288    return NULL;
289  }
290  else if(part==2)
291  { // example
292    if ( pi->data.s.example_lineno == 0)
293      return NULL; // example part does not exist
294    // load example
295    fseek(fp, pi->data.s.example_start, SEEK_SET);
296    /*char *dummy=*/ (void) fgets(buf, sizeof(buf), fp); // skip line with "example"
297    procbuflen = pi->data.s.proc_end - pi->data.s.example_start - strlen(buf);
298    //Print("Example=%ld-%ld=%d\n", pi->data.s.proc_end,
299    //  pi->data.s.example_start, procbuflen);
300    s = (char *)omAlloc(procbuflen+14);
301    myfread(s, procbuflen, 1, fp);
302    s[procbuflen] = '\0';
303    strcat(s+procbuflen-3, "\n;return();\n\n" );
304    p=(char *)strchr(s,'{');
305    if (p!=NULL) *p=' ';
306    return(s);
307  }
308  return NULL;
309}
310
311BOOLEAN iiAllStart(procinfov pi, char *p,feBufferTypes t, int l)
312{
313  // see below:
314  BITSET save1=si_opt_1;
315  BITSET save2=si_opt_2;
316  newBuffer( omStrDup(p /*pi->data.s.body*/), t /*BT_proc*/,
317               pi, l );
318  BOOLEAN err=yyparse();
319  if (sLastPrinted.rtyp!=0)
320  {
321    sLastPrinted.CleanUp();
322  }
323  // the access to optionStruct and verboseStruct do not work
324  // on x86_64-Linux for pic-code
325  if ((TEST_V_ALLWARN) &&
326  (t==BT_proc) &&
327  ((save1!=si_opt_1)||(save2!=si_opt_2)) &&
328  (pi->libname!=NULL) && (pi->libname[0]!='\0'))
329  {
330    if ((pi->libname!=NULL) && (pi->libname[0]!='\0'))
331      Warn("option changed in proc %s from %s",pi->procname,pi->libname);
332    else
333      Warn("option changed in proc %s",pi->procname);
334    int i;
335    for (i=0; optionStruct[i].setval!=0; i++)
336    {
337      if ((optionStruct[i].setval & si_opt_1)
338      && (!(optionStruct[i].setval & save1)))
339      {
340          Print(" +%s",optionStruct[i].name);
341      }
342      if (!(optionStruct[i].setval & si_opt_1)
343      && ((optionStruct[i].setval & save1)))
344      {
345          Print(" -%s",optionStruct[i].name);
346      }
347    }
348    for (i=0; verboseStruct[i].setval!=0; i++)
349    {
350      if ((verboseStruct[i].setval & si_opt_2)
351      && (!(verboseStruct[i].setval & save2)))
352      {
353          Print(" +%s",verboseStruct[i].name);
354      }
355      if (!(verboseStruct[i].setval & si_opt_2)
356      && ((verboseStruct[i].setval & save2)))
357      {
358          Print(" -%s",verboseStruct[i].name);
359      }
360    }
361    PrintLn();
362  }
363  return err;
364}
365/*2
366* start a proc
367* parameters are built as exprlist
368* TODO:interrupt
369* return FALSE on success, TRUE if an error occurs
370*/
371BOOLEAN iiPStart(idhdl pn, leftv v)
372{
373  procinfov pi=NULL;
374  int old_echo=si_echo;
375  BOOLEAN err=FALSE;
376  char save_flags=0;
377
378  /* init febase ======================================== */
379  /* we do not enter this case if filename != NULL !! */
380  if (pn!=NULL)
381  {
382    pi = IDPROC(pn);
383    if(pi!=NULL)
384    {
385      save_flags=pi->trace_flag;
386      if( pi->data.s.body==NULL )
387      {
388        iiGetLibProcBuffer(pi);
389        if (pi->data.s.body==NULL) return TRUE;
390      }
391//      omUpdateInfo();
392//      int m=om_Info.UsedBytes;
393//      Print("proc %s, mem=%d\n",IDID(pn),m);
394    }
395  }
396  else return TRUE;
397  /* generate argument list ======================================*/
398  //iiCurrArgs should be NULL here, as the assignment for the parameters
399  // of the prevouis call are already done befor calling another routine
400  if (v!=NULL)
401  {
402    iiCurrArgs=(leftv)omAllocBin(sleftv_bin);
403    memcpy(iiCurrArgs,v,sizeof(sleftv)); // keeps track of v->next etc.
404    memset(v,0,sizeof(sleftv));
405  }
406  else
407  {
408    iiCurrArgs=NULL;
409  }
410  iiCurrProc=pn;
411  /* start interpreter ======================================*/
412  myynest++;
413  if (myynest > SI_MAX_NEST)
414  {
415    WerrorS("nesting too deep");
416    err=TRUE;
417  }
418  else
419  {
420    err=iiAllStart(pi,pi->data.s.body,BT_proc,pi->data.s.body_lineno-(v!=NULL));
421
422    if (iiLocalRing[myynest-1] != currRing)
423    {
424      if (iiRETURNEXPR.RingDependend())
425      {
426        //idhdl hn;
427        const char *n;
428        const char *o;
429        idhdl nh=NULL, oh=NULL;
430        if (iiLocalRing[myynest-1]!=NULL)
431          oh=rFindHdl(iiLocalRing[myynest-1],NULL);
432        if (oh!=NULL)          o=oh->id;
433        else                   o="none";
434        if (currRing!=NULL)
435          nh=rFindHdl(currRing,NULL);
436        if (nh!=NULL)          n=nh->id;
437        else                   n="none";
438        Werror("ring change during procedure call %s: %s -> %s (level %d)",pi->procname,o,n,myynest);
439        iiRETURNEXPR.CleanUp();
440        err=TRUE;
441      }
442      currRing=iiLocalRing[myynest-1];
443    }
444    if ((currRing==NULL)
445    && (currRingHdl!=NULL))
446      currRing=IDRING(currRingHdl);
447    else
448    if ((currRing!=NULL) &&
449      ((currRingHdl==NULL)||(IDRING(currRingHdl)!=currRing)
450       ||(IDLEV(currRingHdl)>=myynest-1)))
451    {
452      rSetHdl(rFindHdl(currRing,NULL));
453      iiLocalRing[myynest-1]=NULL;
454    }
455    //Print("kill locals for %s (level %d)\n",IDID(pn),myynest);
456    killlocals(myynest);
457#ifndef SING_NDEBUG
458    checkall();
459#endif
460    //Print("end kill locals for %s (%d)\n",IDID(pn),myynest);
461  }
462  myynest--;
463  si_echo=old_echo;
464  if (pi!=NULL)
465    pi->trace_flag=save_flags;
466//  omUpdateInfo();
467//  int m=om_Info.UsedBytes;
468//  Print("exit %s, mem=%d\n",IDID(pn),m);
469  return err;
470}
471
472ring    *iiLocalRing;
473sleftv  iiRETURNEXPR;
474int     iiRETURNEXPR_len=0;
475
476#ifdef RDEBUG
477static void iiShowLevRings()
478{
479  int i;
480  for (i=0;i<=myynest;i++)
481  {
482    Print("lev %d:",i);
483    if (iiLocalRing[i]==NULL) PrintS("NULL");
484    else                      Print("%lx",(long)iiLocalRing[i]);
485    PrintLn();
486  }
487  if (currRing==NULL) PrintS("curr:NULL\n");
488  else                Print ("curr:%lx\n",(long)currRing);
489}
490#endif /* RDEBUG */
491
492static void iiCheckNest()
493{
494  if (myynest >= iiRETURNEXPR_len-1)
495  {
496    iiLocalRing=(ring *)omreallocSize(iiLocalRing,
497                                   iiRETURNEXPR_len*sizeof(ring),
498                                   (iiRETURNEXPR_len+16)*sizeof(ring));
499    memset(&(iiLocalRing[iiRETURNEXPR_len]),0,16*sizeof(ring));
500    iiRETURNEXPR_len+=16;
501  }
502}
503BOOLEAN iiMake_proc(idhdl pn, package pack, leftv sl)
504{
505  int err;
506  procinfov pi = IDPROC(pn);
507  if(pi->is_static && myynest==0)
508  {
509    Werror("'%s::%s()' is a local procedure and cannot be accessed by an user.",
510           pi->libname, pi->procname);
511    return TRUE;
512  }
513  iiCheckNest();
514  iiLocalRing[myynest]=currRing;
515  //Print("currRing(%d):%s(%x) in %s\n",myynest,IDID(currRingHdl),currRing,IDID(pn));
516  iiRETURNEXPR.Init();
517  procstack->push(pi->procname);
518  if ((traceit&TRACE_SHOW_PROC)
519  || (pi->trace_flag&TRACE_SHOW_PROC))
520  {
521    if (traceit&TRACE_SHOW_LINENO) PrintLn();
522    Print("entering%-*.*s %s (level %d)\n",myynest*2,myynest*2," ",IDID(pn),myynest);
523  }
524#ifdef RDEBUG
525  if (traceit&TRACE_SHOW_RINGS) iiShowLevRings();
526#endif
527  switch (pi->language)
528  {
529    default:
530    case LANG_NONE:
531                 WerrorS("undefined proc");
532                 err=TRUE;
533                 break;
534
535    case LANG_SINGULAR:
536                 if ((pi->pack!=NULL)&&(currPack!=pi->pack))
537                 {
538                   currPack=pi->pack;
539                   iiCheckPack(currPack);
540                   currPackHdl=packFindHdl(currPack);
541                   //Print("set pack=%s\n",IDID(currPackHdl));
542                 }
543                 else if ((pack!=NULL)&&(currPack!=pack))
544                 {
545                   currPack=pack;
546                   iiCheckPack(currPack);
547                   currPackHdl=packFindHdl(currPack);
548                   //Print("set pack=%s\n",IDID(currPackHdl));
549                 }
550                 err=iiPStart(pn,sl);
551                 break;
552    case LANG_C:
553                 leftv res = (leftv)omAlloc0Bin(sleftv_bin);
554                 err = (pi->data.o.function)(res, sl);
555                 memcpy(&iiRETURNEXPR,res,sizeof(iiRETURNEXPR));
556                 omFreeBin((ADDRESS)res,  sleftv_bin);
557                 break;
558  }
559  if ((traceit&TRACE_SHOW_PROC)
560  || (pi->trace_flag&TRACE_SHOW_PROC))
561  {
562    if (traceit&TRACE_SHOW_LINENO) PrintLn();
563    Print("leaving %-*.*s %s (level %d)\n",myynest*2,myynest*2," ",IDID(pn),myynest);
564  }
565  //const char *n="NULL";
566  //if (currRingHdl!=NULL) n=IDID(currRingHdl);
567  //Print("currRing(%d):%s(%x) after %s\n",myynest,n,currRing,IDID(pn));
568#ifdef RDEBUG
569  if (traceit&TRACE_SHOW_RINGS) iiShowLevRings();
570#endif
571  if (err)
572  {
573    iiRETURNEXPR.CleanUp();
574    //iiRETURNEXPR.Init(); //done by CleanUp
575  }
576  if (iiCurrArgs!=NULL)
577  {
578    if (!err) Warn("too many arguments for %s",IDID(pn));
579    iiCurrArgs->CleanUp();
580    omFreeBin((ADDRESS)iiCurrArgs, sleftv_bin);
581    iiCurrArgs=NULL;
582  }
583  procstack->pop();
584  if (err)
585    return TRUE;
586  return FALSE;
587}
588
589/*2
590* start an example (as a proc),
591* destroys the string 'example'
592*/
593BOOLEAN iiEStart(char* example, procinfo *pi)
594{
595  BOOLEAN err;
596  int old_echo=si_echo;
597
598  iiCheckNest();
599  procstack->push(example);
600  iiLocalRing[myynest]=currRing;
601  if (traceit&TRACE_SHOW_PROC)
602  {
603    if (traceit&TRACE_SHOW_LINENO) printf("\n");
604    printf("entering example (level %d)\n",myynest);
605  }
606  myynest++;
607
608  err=iiAllStart(pi,example,BT_example,(pi != NULL ? pi->data.s.example_lineno: 0));
609
610  killlocals(myynest);
611  myynest--;
612  si_echo=old_echo;
613  if (traceit&TRACE_SHOW_PROC)
614  {
615    if (traceit&TRACE_SHOW_LINENO) printf("\n");
616    printf("leaving  -example- (level %d)\n",myynest);
617  }
618  if (iiLocalRing[myynest] != currRing)
619  {
620    if (iiLocalRing[myynest]!=NULL)
621    {
622      rSetHdl(rFindHdl(iiLocalRing[myynest],NULL));
623      iiLocalRing[myynest]=NULL;
624    }
625    else
626    {
627      currRingHdl=NULL;
628      currRing=NULL;
629    }
630  }
631  procstack->pop();
632  return err;
633}
634
635
636extern "C"
637{
638#  define SI_GET_BUILTIN_MOD_INIT0(name) int SI_MOD_INIT0(name)(SModulFunctions*);
639          SI_FOREACH_BUILTIN(SI_GET_BUILTIN_MOD_INIT0)
640#  undef  SI_GET_BUILTIN_MOD_INIT0
641};
642
643
644SModulFunc_t
645iiGetBuiltinModInit(const char* libname)
646{
647#  define SI_GET_BUILTIN_MOD_INIT(name) if (strcmp(libname, #name ".so") == 0){ return SI_MOD_INIT0(name); }
648          SI_FOREACH_BUILTIN(SI_GET_BUILTIN_MOD_INIT)
649#  undef  SI_GET_BUILTIN_MOD_INIT
650
651  return NULL;
652}
653
654
655
656
657/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
658BOOLEAN iiTryLoadLib(leftv v, const char *id)
659{
660  BOOLEAN LoadResult = TRUE;
661  char libnamebuf[1024];
662  char *libname = (char *)omAlloc(strlen(id)+5);
663  const char *suffix[] = { "", ".lib", ".so", ".sl", NULL };
664  int i = 0;
665  // FILE *fp;
666  // package pack;
667  // idhdl packhdl;
668  lib_types LT;
669  for(i=0; suffix[i] != NULL; i++)
670  {
671    sprintf(libname, "%s%s", id, suffix[i]);
672    *libname = mytolower(*libname);
673    if((LT = type_of_LIB(libname, libnamebuf)) > LT_NOTFOUND)
674    {
675      char *s=omStrDup(libname);
676      #ifdef HAVE_DYNAMIC_LOADING
677      char libnamebuf[1024];
678      #endif
679
680      if (LT==LT_SINGULAR)
681        LoadResult = iiLibCmd(s, FALSE, FALSE,TRUE);
682      #ifdef HAVE_DYNAMIC_LOADING
683      else if ((LT==LT_ELF) || (LT==LT_HPUX))
684        LoadResult = load_modules(s,libnamebuf,FALSE);
685      #endif
686      else if (LT==LT_BUILTIN)
687      {
688        LoadResult=load_builtin(s,FALSE, iiGetBuiltinModInit(s));
689      }
690      if(!LoadResult )
691      {
692        v->name = iiConvName(libname);
693        break;
694      }
695    }
696  }
697  omFree(libname);
698  return LoadResult;
699}
700
701/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
702/* check, if library lib has already been loaded
703   if yes, writes filename of lib into where and returns TRUE,
704      no, returns FALSE
705*/
706BOOLEAN iiLocateLib(const char* lib, char* where)
707{
708  char *plib = iiConvName(lib);
709  idhdl pl = basePack->idroot->get(plib,0);
710  if( (pl!=NULL) && (IDTYP(pl)==PACKAGE_CMD) &&
711    (IDPACKAGE(pl)->language == LANG_SINGULAR))
712  {
713    strncpy(where,IDPACKAGE(pl)->libname,127);
714    return TRUE;
715  }
716  else
717    return FALSE;;
718}
719
720BOOLEAN iiLibCmd( char *newlib, BOOLEAN autoexport, BOOLEAN tellerror, BOOLEAN force )
721{
722  char libnamebuf[1024];
723  // procinfov pi;
724  // idhdl h;
725  idhdl pl;
726  // idhdl hl;
727  // long pos = 0L;
728  char *plib = iiConvName(newlib);
729  FILE * fp = feFopen( newlib, "r", libnamebuf, tellerror );
730  // int lines = 1;
731  BOOLEAN LoadResult = TRUE;
732
733  if (fp==NULL)
734  {
735    return TRUE;
736  }
737  pl = basePack->idroot->get(plib,0);
738  if (pl==NULL)
739  {
740    pl = enterid( plib,0, PACKAGE_CMD,
741                  &(basePack->idroot), TRUE );
742    IDPACKAGE(pl)->language = LANG_SINGULAR;
743    IDPACKAGE(pl)->libname=omStrDup(newlib);
744  }
745  else
746  {
747    if(IDTYP(pl)!=PACKAGE_CMD)
748    {
749      WarnS("not of type package.");
750      fclose(fp);
751      return TRUE;
752    }
753    if (!force) return FALSE;
754  }
755  LoadResult = iiLoadLIB(fp, libnamebuf, newlib, pl, autoexport, tellerror);
756  omFree((ADDRESS)newlib);
757
758  if(!LoadResult) IDPACKAGE(pl)->loaded = TRUE;
759  omFree((ADDRESS)plib);
760
761 return LoadResult;
762}
763/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
764static void iiCleanProcs(idhdl &root)
765{
766  idhdl prev=NULL;
767  loop
768  {
769    if (root==NULL) return;
770    if (IDTYP(root)==PROC_CMD)
771    {
772      procinfo *pi=(procinfo*)IDDATA(root);
773      if ((pi->language == LANG_SINGULAR)
774      && (pi->data.s.body_start == 0L))
775      {
776        // procinfo data incorrect:
777        // - no proc body can start at the beginning of the file
778        killhdl(root);
779        if (prev==NULL)
780          root=IDROOT;
781        else
782        {
783          root=prev;
784          prev=NULL;
785        }
786        continue;
787      }
788    }
789    prev=root;
790    root=IDNEXT(root);
791  }
792}
793static void iiRunInit(package p)
794{
795  idhdl h=p->idroot->get("mod_init",0);
796  if (h==NULL) return;
797  if (IDTYP(h)==PROC_CMD)
798  {
799    int save=yylineno;
800    myynest++;
801    // procinfo *pi=(procinfo*)IDDATA(h);
802    //PrintS("mod_init found\n");
803    iiMake_proc(h,p,NULL);
804    myynest--;
805    yylineno=save;
806  }
807}
808/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
809BOOLEAN iiLoadLIB(FILE *fp, const char *libnamebuf, const char*newlib,
810             idhdl pl, BOOLEAN autoexport, BOOLEAN tellerror)
811{
812  extern FILE *yylpin;
813  libstackv ls_start = library_stack;
814  lib_style_types lib_style;
815
816  yylpin = fp;
817  #if YYLPDEBUG > 1
818  print_init();
819  #endif
820  extern int lpverbose;
821  if (BVERBOSE(V_DEBUG_LIB)) lpverbose=1;
822  else lpverbose=0;
823  // yylplex sets also text_buffer
824  if (text_buffer!=NULL) *text_buffer='\0';
825  yylplex(newlib, libnamebuf, &lib_style, pl, autoexport);
826  if(yylp_errno)
827  {
828    Werror("Library %s: ERROR occurred: in line %d, %d.", newlib, yylplineno,
829         current_pos(0));
830    if(yylp_errno==YYLP_BAD_CHAR)
831    {
832      Werror(yylp_errlist[yylp_errno], *text_buffer, yylplineno);
833      omFree((ADDRESS)text_buffer);
834      text_buffer=NULL;
835    }
836    else
837      Werror(yylp_errlist[yylp_errno], yylplineno);
838    WerrorS("Cannot load library,... aborting.");
839    reinit_yylp();
840    fclose( yylpin );
841    iiCleanProcs(IDROOT);
842    return TRUE;
843  }
844  if (BVERBOSE(V_LOAD_LIB))
845    Print( "// ** loaded %s %s\n", libnamebuf, text_buffer);
846  if( (lib_style == OLD_LIBSTYLE) && (BVERBOSE(V_LOAD_LIB)))
847  {
848    Warn( "library %s has old format. This format is still accepted,", newlib);
849    Warn( "but for functionality you may wish to change to the new");
850    Warn( "format. Please refer to the manual for further information.");
851  }
852  reinit_yylp();
853  fclose( yylpin );
854  fp = NULL;
855  iiRunInit(IDPACKAGE(pl));
856
857  {
858    libstackv ls;
859    for(ls = library_stack; (ls != NULL) && (ls != ls_start); )
860    {
861      if(ls->to_be_done)
862      {
863        ls->to_be_done=FALSE;
864        iiLibCmd(ls->get(),autoexport,tellerror,FALSE);
865        ls = ls->pop(newlib);
866      }
867    }
868#if 0
869    PrintS("--------------------\n");
870    for(ls = library_stack; ls != NULL; ls = ls->next)
871    {
872      Print("%s: LIB-stack:(%d), %s %s\n", newlib, ls->cnt, ls->get(),
873        ls->to_be_done ? "not loaded" : "loaded");
874    }
875    PrintS("--------------------\n");
876#endif
877  }
878
879  if(fp != NULL) fclose(fp);
880  return FALSE;
881}
882
883
884/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
885procinfo *iiInitSingularProcinfo(procinfov pi, const char *libname,
886              const char *procname, int, long pos, BOOLEAN pstatic)
887{
888  memset(pi,0,sizeof(*pi));
889  pi->libname = omStrDup(libname);
890  pi->procname = omStrDup(procname);
891  pi->language = LANG_SINGULAR;
892  pi->ref = 1;
893  pi->is_static = pstatic;
894  pi->data.s.proc_start = pos;
895  return(pi);
896}
897
898/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
899int iiAddCproc(const char *libname, const char *procname, BOOLEAN pstatic,
900               BOOLEAN(*func)(leftv res, leftv v))
901{
902  procinfov pi;
903  idhdl h;
904
905  #ifndef SING_NDEBUG
906  int dummy;
907  if (IsCmd(procname,dummy))
908  {
909    Werror(">>%s< is a reserved name",procname);
910    return 0;
911  }
912  #endif
913
914  h=IDROOT->get(procname,0);
915  if ((h!=NULL)
916  && (IDTYP(h)==PROC_CMD))
917  {
918    pi = IDPROC(h);
919    if ((pi->language == LANG_SINGULAR)
920    &&(BVERBOSE(V_REDEFINE)))
921      Warn("extend `%s`",procname);
922  }
923  else
924  {
925    h = enterid(procname,0, PROC_CMD, &IDROOT, TRUE);
926  }
927  if ( h!= NULL )
928  {
929    pi = IDPROC(h);
930    if((pi->language == LANG_SINGULAR)
931    ||(pi->language == LANG_NONE))
932    {
933      omfree(pi->libname);
934      pi->libname = omStrDup(libname);
935      omfree(pi->procname);
936      pi->procname = omStrDup(procname);
937      pi->language = LANG_C;
938      pi->ref = 1;
939      pi->is_static = pstatic;
940      pi->data.o.function = func;
941    }
942    else if(pi->language == LANG_C)
943    {
944      if(pi->data.o.function == func)
945      {
946        pi->ref++;
947      }
948      else
949      {
950        omfree(pi->libname);
951        pi->libname = omStrDup(libname);
952        omfree(pi->procname);
953        pi->procname = omStrDup(procname);
954        pi->language = LANG_C;
955        pi->ref = 1;
956        pi->is_static = pstatic;
957        pi->data.o.function = func;
958      }
959    }
960    else
961      Warn("internal error: unknown procedure type %d",pi->language);
962    return(1);
963  }
964  else
965  {
966    WarnS("iiAddCproc: failed.");
967  }
968  return(0);
969}
970
971int iiAddCprocTop(const char *libname, const char *procname, BOOLEAN pstatic,
972               BOOLEAN(*func)(leftv res, leftv v))
973{
974  int r=iiAddCproc(libname,procname,pstatic,func);
975  package s=currPack;
976  currPack=basePack;
977  if (r) r=iiAddCproc(libname,procname,pstatic,func);
978  currPack=s;
979  return r;
980}
981
982/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
983#ifdef HAVE_DYNAMIC_LOADING
984BOOLEAN load_modules(const char *newlib, char *fullname, BOOLEAN autoexport)
985{
986#ifdef HAVE_STATIC
987  WerrorS("mod_init: static version can not load modules");
988  return TRUE;
989#else
990/*
991  typedef int (*fktn_t)(int(*iiAddCproc)(const char *libname, const char *procname,
992                               BOOLEAN pstatic,
993                               BOOLEAN(*func)(leftv res, leftv v)));
994*/
995  SModulFunc_t fktn;
996  idhdl pl;
997  char *plib = iiConvName(newlib);
998  BOOLEAN RET=TRUE;
999  int token;
1000  char FullName[256];
1001
1002  memset(FullName,0,256);
1003
1004  if( *fullname != '/' &&  *fullname != '.' )
1005    sprintf(FullName, "./%s", newlib);
1006  else strncpy(FullName, fullname,255);
1007
1008
1009  if(IsCmd(plib, token))
1010  {
1011    Werror("'%s' is resered identifier\n", plib);
1012    goto load_modules_end;
1013  }
1014  pl = basePack->idroot->get(plib,0); /* packages only in top level
1015                                        (see enterid) */
1016  if ((pl!=NULL)
1017  &&(IDTYP(pl)==PACKAGE_CMD))
1018  {
1019    if(IDPACKAGE(pl)->language==LANG_C)
1020    {
1021      if (BVERBOSE(V_LOAD_LIB)) Warn( "%s already loaded as package", newlib);
1022      omFree(plib);
1023      return FALSE;
1024    }
1025  }
1026  else
1027  {
1028    pl = enterid( plib,0, PACKAGE_CMD, &IDROOT, TRUE );
1029    IDPACKAGE(pl)->libname=omStrDup(newlib);
1030  }
1031  IDPACKAGE(pl)->language = LANG_C;
1032  if (dynl_check_opened(FullName))
1033  {
1034    if (BVERBOSE(V_LOAD_LIB)) Warn( "%s already loaded as C library", fullname);
1035    return FALSE;
1036  }
1037  if((IDPACKAGE(pl)->handle=dynl_open(FullName))==(void *)NULL)
1038  {
1039    Werror("dynl_open failed:%s", dynl_error());
1040    Werror("%s not found", newlib);
1041    killhdl2(pl,&(basePack->idroot),NULL); // remove package
1042    goto load_modules_end;
1043  }
1044  else
1045  {
1046    SModulFunctions sModulFunctions;
1047
1048    package s=currPack;
1049    currPack=IDPACKAGE(pl);
1050    fktn = (SModulFunc_t)dynl_sym(IDPACKAGE(pl)->handle, "mod_init");
1051    if( fktn!= NULL)
1052    {
1053      sModulFunctions.iiArithAddCmd = iiArithAddCmd;
1054      if (autoexport) sModulFunctions.iiAddCproc = iiAddCprocTop;
1055      else            sModulFunctions.iiAddCproc = iiAddCproc;
1056      int ver=(*fktn)(&sModulFunctions);
1057      if (ver==MAX_TOK)
1058      {
1059        if (BVERBOSE(V_LOAD_LIB)) Print( "// ** loaded %s\n", fullname);
1060      }
1061      else
1062      {
1063        Warn("loaded %s for a different version of Singular(expected MAX_TOK: %d, got %d)",fullname,MAX_TOK,ver);
1064      }
1065      currPack->loaded=1;
1066      currPack=s;
1067      RET=FALSE;
1068    }
1069    else
1070    {
1071      Werror("mod_init not found:: %s\nThis is probably not a dynamic module for Singular!\n", dynl_error());
1072      killhdl2(pl,&(basePack->idroot),NULL); // remove package
1073    }
1074  }
1075
1076  load_modules_end:
1077  return RET;
1078#endif /*STATIC */
1079}
1080#endif /* HAVE_DYNAMIC_LOADING */
1081/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
1082BOOLEAN load_builtin(const char *newlib, BOOLEAN autoexport, SModulFunc_t init)
1083{
1084  int iiAddCproc(const char *libname, const char *procname, BOOLEAN pstatic,
1085                 BOOLEAN(*func)(leftv res, leftv v));
1086/*
1087  typedef int (*fktn_t)(int(*iiAddCproc)(const char *libname, const char *procname,
1088                               BOOLEAN pstatic,
1089                               BOOLEAN(*func)(leftv res, leftv v)));
1090*/
1091  // SModulFunc_t fktn;
1092  idhdl pl;
1093  char *plib = iiConvName(newlib);
1094  // BOOLEAN RET=TRUE;
1095  // int token;
1096
1097  pl = basePack->idroot->get(plib,0); // search PACKAGE only in Top
1098  if ((pl!=NULL)
1099  &&(IDTYP(pl)==PACKAGE_CMD))
1100  {
1101    if(IDPACKAGE(pl)->language==LANG_C)
1102    {
1103      if (BVERBOSE(V_LOAD_LIB)) Warn( "(builtin) %s already loaded", newlib);
1104      omFree(plib);
1105      return FALSE;
1106    }
1107  }
1108  else
1109  {
1110    pl = enterid( plib,0, PACKAGE_CMD, &IDROOT, TRUE );
1111    IDPACKAGE(pl)->libname=omStrDup(newlib);
1112  }
1113  IDPACKAGE(pl)->language = LANG_C;
1114
1115  IDPACKAGE(pl)->handle=(void *)NULL;
1116  SModulFunctions sModulFunctions;
1117
1118  package s=currPack;
1119  currPack=IDPACKAGE(pl);
1120  if( init!= NULL)
1121  {
1122    sModulFunctions.iiArithAddCmd = iiArithAddCmd;
1123    if (autoexport) sModulFunctions.iiAddCproc = iiAddCprocTop;
1124    else            sModulFunctions.iiAddCproc = iiAddCproc;
1125    (*init)(&sModulFunctions);
1126  }
1127  if (BVERBOSE(V_LOAD_LIB)) Print( "// ** loaded (builtin) %s \n", newlib);
1128  currPack->loaded=1;
1129  currPack=s;
1130
1131  return FALSE;
1132}
1133/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
1134void module_help_main(const char *newlib,const char *help)
1135{
1136  char *plib = iiConvName(newlib);
1137  idhdl pl = basePack->idroot->get(plib,0);
1138  if ((pl==NULL)||(IDTYP(pl)!=PACKAGE_CMD))
1139    Werror(">>%s<< is not a package (trying to add package help)",plib);
1140  else
1141  {
1142    package s=currPack;
1143    currPack=IDPACKAGE(pl);
1144    idhdl h=enterid(omStrDup("info"),0,STRING_CMD,&IDROOT,FALSE);
1145    IDSTRING(h)=omStrDup(help);
1146    currPack=s;
1147  }
1148}
1149void module_help_proc(const char *newlib,const char *p, const char *help)
1150{
1151  char *plib = iiConvName(newlib);
1152  idhdl pl = basePack->idroot->get(plib,0);
1153  if ((pl==NULL)||(IDTYP(pl)!=PACKAGE_CMD))
1154    Werror(">>%s<< is not a package(trying to add help for %s)",plib,p);
1155  else
1156  {
1157    package s=currPack;
1158    currPack=IDPACKAGE(pl);
1159    char buff[256];
1160    buff[255]='\0';
1161    strncpy(buff,p,255);
1162    strncat(buff,"_help",255-strlen(p));
1163    idhdl h=enterid(omStrDup(buff),0,STRING_CMD,&IDROOT,FALSE);
1164    IDSTRING(h)=omStrDup(help);
1165    currPack=s;
1166  }
1167}
1168/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
1169
1170#ifdef HAVE_DYNAMIC_LOADING
1171// loads a dynamic module from the binary path and returns a named function
1172// returns NULL, if something fails
1173void* binary_module_function(const char* newlib, const char* funcname)
1174{
1175  void* result = NULL;
1176
1177  const char* bin_dir = feGetResource('b');
1178  if (!bin_dir)  { return NULL; }
1179
1180  char path_name[MAXPATHLEN];
1181  sprintf(path_name, "%s%s%s.%s", bin_dir, DIR_SEPP, newlib, MODULE_SUFFIX_STRING);
1182
1183  void* openlib = dynl_open(path_name);
1184  if(!openlib)
1185  {
1186    Werror("dynl_open of %s failed:%s", path_name, dynl_error());
1187    return NULL;
1188  }
1189  result = dynl_sym(openlib, funcname);
1190  if (!result) Werror("%s: %s\n", funcname, dynl_error());
1191
1192  return result;
1193}
1194#endif
1195
1196/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
1197char mytoupper(char c)
1198{
1199  if(c>=97 && c<=(97+26)) c-=32;
1200  return(c);
1201}
1202
1203char mytolower(char c)
1204{
1205  if(c>=65 && c<=(65+26)) c+=32;
1206  return(c);
1207}
1208
1209/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
1210//#if defined(WINNT)
1211//#  define  FS_SEP '\\'
1212//#else
1213//#  define FS_SEP '/'
1214//#endif
1215
1216char *iiConvName(const char *libname)
1217{
1218  char *tmpname = omStrDup(libname);
1219  char *p = strrchr(tmpname, DIR_SEP);
1220  char *r;
1221  if(p==NULL) p = tmpname;
1222  else p++;
1223  r = (char *)strchr(p, '.');
1224  if( r!= NULL) *r = '\0';
1225  r = omStrDup(p);
1226  *r = mytoupper(*r);
1227  // printf("iiConvName: '%s' '%s' => '%s'\n", libname, tmpname, r);
1228  omFree((ADDRESS)tmpname);
1229
1230  return(r);
1231}
1232
1233/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
1234#if 0 /* debug only */
1235void piShowProcList()
1236{
1237  idhdl h;
1238  procinfo *proc;
1239  char *name;
1240
1241  Print( "%-15s  %20s      %s,%s  %s,%s   %s,%s\n", "Library", "function",
1242         "line", "start", "line", "body", "line", "example");
1243  for(h = IDROOT; h != NULL; h = IDNEXT(h))
1244  {
1245    if(IDTYP(h) == PROC_CMD)
1246    {
1247      proc = IDPROC(h);
1248      if(strcmp(proc->procname, IDID(h))!=0)
1249      {
1250        name = (char *)omAlloc(strlen(IDID(h))+strlen(proc->procname)+4);
1251        sprintf(name, "%s -> %s", IDID(h), proc->procname);
1252        Print( "%d %-15s  %20s ", proc->is_static ? 1 : 0, proc->libname, name);
1253        omFree((ADDRESS)name);
1254      }
1255      else
1256        Print( "%d %-15s  %20s ", proc->is_static ? 1 : 0, proc->libname,
1257               proc->procname);
1258      if(proc->language==LANG_SINGULAR)
1259        Print("line %-5ld  %4d,%-5ld  %4d,%-5ld\n",
1260              proc->data.s.proc_start,
1261              proc->data.s.body_lineno, proc->data.s.body_start,
1262              proc->data.s.example_lineno, proc->data.s.example_start);
1263      else if(proc->language==LANG_C)
1264        PrintS("type: object\n");
1265    }
1266  }
1267}
1268#endif
1269
1270/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
1271//char *iiLineNo(char *procname, int lineno)
1272//{
1273//  char buf[256];
1274//  idhdl pn = ggetid(procname);
1275//  procinfo *pi = IDPROC(pn);
1276//
1277//  sprintf(buf, "%s %3d\0", procname, lineno);
1278//  //sprintf(buf, "%s::%s %3d\0", pi->libname, pi->procname,
1279//  //  lineno + pi->data.s.body_lineno);
1280//  return(buf);
1281//}
1282/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
1283#ifdef HAVE_LIBPARSER
1284void libstack::push(const char */*p*/, char *libn)
1285{
1286  libstackv lp;
1287  if( !iiGetLibStatus(libn))
1288  {
1289    for(lp = this;lp!=NULL;lp=lp->next)
1290    {
1291      if(strcmp(lp->get(), libn)==0) break;
1292    }
1293    if(lp==NULL)
1294    {
1295      libstackv ls = (libstack *)omAlloc0Bin(libstack_bin);
1296      ls->next = this;
1297      ls->libname = omStrDup(libn);
1298      ls->to_be_done = TRUE;
1299      if(this != NULL) ls->cnt = this->cnt+1; else ls->cnt = 0;
1300      library_stack = ls;
1301    }
1302  }
1303}
1304
1305libstackv libstack::pop(const char */*p*/)
1306{
1307  libstackv ls = this;
1308  //omFree((ADDRESS)ls->libname);
1309  library_stack = ls->next;
1310  omFreeBin((ADDRESS)ls,  libstack_bin);
1311  return(library_stack);
1312}
1313
1314#endif /* HAVE_LIBPARSER */
1315/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
Note: See TracBrowser for help on using the repository browser.