source: git/Singular/iplib.cc @ 4bada2

spielwiese
Last change on this file since 4bada2 was 951177, checked in by Hans Schoenemann <hannes@…>, 7 years ago
fix: crash at defining proc in .lib and .so twice (LIB"gfan.lib";LIB"gfan.lib";)
  • Property mode set to 100644
File size: 33.4 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, sleftv  * 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  if (v!=NULL)
399  {
400    iiCurrArgs=(leftv)omAllocBin(sleftv_bin);
401    memcpy(iiCurrArgs,v,sizeof(sleftv));
402    memset(v,0,sizeof(sleftv));
403  }
404  else
405  {
406    iiCurrArgs=NULL;
407  }
408  iiCurrProc=pn;
409  /* start interpreter ======================================*/
410  myynest++;
411  if (myynest > SI_MAX_NEST)
412  {
413    WerrorS("nesting too deep");
414    err=TRUE;
415  }
416  else
417  {
418    err=iiAllStart(pi,pi->data.s.body,BT_proc,pi->data.s.body_lineno-(v!=NULL));
419
420    if (iiLocalRing[myynest-1] != currRing)
421    {
422      if (iiRETURNEXPR.RingDependend())
423      {
424        //idhdl hn;
425        const char *n;
426        const char *o;
427        idhdl nh=NULL, oh=NULL;
428        if (iiLocalRing[myynest-1]!=NULL)
429          oh=rFindHdl(iiLocalRing[myynest-1],NULL);
430        if (oh!=NULL)          o=oh->id;
431        else                   o="none";
432        if (currRing!=NULL)
433          nh=rFindHdl(currRing,NULL);
434        if (nh!=NULL)          n=nh->id;
435        else                   n="none";
436        Werror("ring change during procedure call: %s -> %s (level %d)",o,n,myynest);
437        iiRETURNEXPR.CleanUp();
438        err=TRUE;
439      }
440      currRing=iiLocalRing[myynest-1];
441    }
442    if ((currRing==NULL)
443    && (currRingHdl!=NULL))
444      currRing=IDRING(currRingHdl);
445    else
446    if ((currRing!=NULL) &&
447      ((currRingHdl==NULL)||(IDRING(currRingHdl)!=currRing)
448       ||(IDLEV(currRingHdl)>=myynest-1)))
449    {
450      rSetHdl(rFindHdl(currRing,NULL));
451      iiLocalRing[myynest-1]=NULL;
452    }
453    //Print("kill locals for %s (level %d)\n",IDID(pn),myynest);
454    killlocals(myynest);
455#ifndef SING_NDEBUG
456    checkall();
457#endif
458    //Print("end kill locals for %s (%d)\n",IDID(pn),myynest);
459  }
460  myynest--;
461  si_echo=old_echo;
462  if (pi!=NULL)
463    pi->trace_flag=save_flags;
464//  omUpdateInfo();
465//  int m=om_Info.UsedBytes;
466//  Print("exit %s, mem=%d\n",IDID(pn),m);
467  return err;
468}
469
470ring    *iiLocalRing;
471sleftv  iiRETURNEXPR;
472int     iiRETURNEXPR_len=0;
473
474#ifdef RDEBUG
475static void iiShowLevRings()
476{
477  int i;
478  for (i=0;i<=myynest;i++)
479  {
480    Print("lev %d:",i);
481    if (iiLocalRing[i]==NULL) PrintS("NULL");
482    else                      Print("%lx",(long)iiLocalRing[i]);
483    PrintLn();
484  }
485  if (currRing==NULL) PrintS("curr:NULL\n");
486  else                Print ("curr:%lx\n",(long)currRing);
487}
488#endif /* RDEBUG */
489
490static void iiCheckNest()
491{
492  if (myynest >= iiRETURNEXPR_len-1)
493  {
494    iiLocalRing=(ring *)omreallocSize(iiLocalRing,
495                                   iiRETURNEXPR_len*sizeof(ring),
496                                   (iiRETURNEXPR_len+16)*sizeof(ring));
497    memset(&(iiLocalRing[iiRETURNEXPR_len]),0,16*sizeof(ring));
498    iiRETURNEXPR_len+=16;
499  }
500}
501BOOLEAN iiMake_proc(idhdl pn, package pack, sleftv* sl)
502{
503  int err;
504  procinfov pi = IDPROC(pn);
505  if(pi->is_static && myynest==0)
506  {
507    Werror("'%s::%s()' is a local procedure and cannot be accessed by an user.",
508           pi->libname, pi->procname);
509    return TRUE;
510  }
511  iiCheckNest();
512  iiLocalRing[myynest]=currRing;
513  //Print("currRing(%d):%s(%x) in %s\n",myynest,IDID(currRingHdl),currRing,IDID(pn));
514  iiRETURNEXPR.Init();
515  procstack->push(pi->procname);
516  if ((traceit&TRACE_SHOW_PROC)
517  || (pi->trace_flag&TRACE_SHOW_PROC))
518  {
519    if (traceit&TRACE_SHOW_LINENO) PrintLn();
520    Print("entering%-*.*s %s (level %d)\n",myynest*2,myynest*2," ",IDID(pn),myynest);
521  }
522#ifdef RDEBUG
523  if (traceit&TRACE_SHOW_RINGS) iiShowLevRings();
524#endif
525  switch (pi->language)
526  {
527    default:
528    case LANG_NONE:
529                 WerrorS("undefined proc");
530                 err=TRUE;
531                 break;
532
533    case LANG_SINGULAR:
534                 if ((pi->pack!=NULL)&&(currPack!=pi->pack))
535                 {
536                   currPack=pi->pack;
537                   iiCheckPack(currPack);
538                   currPackHdl=packFindHdl(currPack);
539                   //Print("set pack=%s\n",IDID(currPackHdl));
540                 }
541                 else if ((pack!=NULL)&&(currPack!=pack))
542                 {
543                   currPack=pack;
544                   iiCheckPack(currPack);
545                   currPackHdl=packFindHdl(currPack);
546                   //Print("set pack=%s\n",IDID(currPackHdl));
547                 }
548                 err=iiPStart(pn,sl);
549                 break;
550    case LANG_C:
551                 leftv res = (leftv)omAlloc0Bin(sleftv_bin);
552                 err = (pi->data.o.function)(res, sl);
553                 memcpy(&iiRETURNEXPR,res,sizeof(iiRETURNEXPR));
554                 omFreeBin((ADDRESS)res,  sleftv_bin);
555                 break;
556  }
557  if ((traceit&TRACE_SHOW_PROC)
558  || (pi->trace_flag&TRACE_SHOW_PROC))
559  {
560    if (traceit&TRACE_SHOW_LINENO) PrintLn();
561    Print("leaving %-*.*s %s (level %d)\n",myynest*2,myynest*2," ",IDID(pn),myynest);
562  }
563  //const char *n="NULL";
564  //if (currRingHdl!=NULL) n=IDID(currRingHdl);
565  //Print("currRing(%d):%s(%x) after %s\n",myynest,n,currRing,IDID(pn));
566#ifdef RDEBUG
567  if (traceit&TRACE_SHOW_RINGS) iiShowLevRings();
568#endif
569  if (err)
570  {
571    iiRETURNEXPR.CleanUp();
572    //iiRETURNEXPR.Init(); //done by CleanUp
573  }
574  if (iiCurrArgs!=NULL)
575  {
576    if (!err) Warn("too many arguments for %s",IDID(pn));
577    iiCurrArgs->CleanUp();
578    omFreeBin((ADDRESS)iiCurrArgs, sleftv_bin);
579    iiCurrArgs=NULL;
580  }
581  procstack->pop();
582  if (err)
583    return TRUE;
584  return FALSE;
585}
586
587/*2
588* start an example (as a proc),
589* destroys the string 'example'
590*/
591BOOLEAN iiEStart(char* example, procinfo *pi)
592{
593  BOOLEAN err;
594  int old_echo=si_echo;
595
596  iiCheckNest();
597  procstack->push(example);
598  iiLocalRing[myynest]=currRing;
599  if (traceit&TRACE_SHOW_PROC)
600  {
601    if (traceit&TRACE_SHOW_LINENO) printf("\n");
602    printf("entering example (level %d)\n",myynest);
603  }
604  myynest++;
605
606  err=iiAllStart(pi,example,BT_example,(pi != NULL ? pi->data.s.example_lineno: 0));
607
608  killlocals(myynest);
609  myynest--;
610  si_echo=old_echo;
611  if (traceit&TRACE_SHOW_PROC)
612  {
613    if (traceit&TRACE_SHOW_LINENO) printf("\n");
614    printf("leaving  -example- (level %d)\n",myynest);
615  }
616  if (iiLocalRing[myynest] != currRing)
617  {
618    if (iiLocalRing[myynest]!=NULL)
619    {
620      rSetHdl(rFindHdl(iiLocalRing[myynest],NULL));
621      iiLocalRing[myynest]=NULL;
622    }
623    else
624    {
625      currRingHdl=NULL;
626      currRing=NULL;
627    }
628  }
629  procstack->pop();
630  return err;
631}
632
633
634extern "C"
635{
636#  define SI_GET_BUILTIN_MOD_INIT0(name) int SI_MOD_INIT0(name)(SModulFunctions*);
637          SI_FOREACH_BUILTIN(SI_GET_BUILTIN_MOD_INIT0)
638#  undef  SI_GET_BUILTIN_MOD_INIT0
639};
640
641
642SModulFunc_t
643iiGetBuiltinModInit(const char* libname)
644{
645#  define SI_GET_BUILTIN_MOD_INIT(name) if (strcmp(libname, #name ".so") == 0){ return SI_MOD_INIT0(name); }
646          SI_FOREACH_BUILTIN(SI_GET_BUILTIN_MOD_INIT)
647#  undef  SI_GET_BUILTIN_MOD_INIT
648
649  return NULL;
650}
651
652
653
654
655/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
656BOOLEAN iiTryLoadLib(leftv v, const char *id)
657{
658  BOOLEAN LoadResult = TRUE;
659  char libnamebuf[128];
660  char *libname = (char *)omAlloc(strlen(id)+5);
661  const char *suffix[] = { "", ".lib", ".so", ".sl", NULL };
662  int i = 0;
663  // FILE *fp;
664  // package pack;
665  // idhdl packhdl;
666  lib_types LT;
667  for(i=0; suffix[i] != NULL; i++)
668  {
669    sprintf(libname, "%s%s", id, suffix[i]);
670    *libname = mytolower(*libname);
671    if((LT = type_of_LIB(libname, libnamebuf)) > LT_NOTFOUND)
672    {
673      char *s=omStrDup(libname);
674      #ifdef HAVE_DYNAMIC_LOADING
675      char libnamebuf[256];
676      #endif
677
678      if (LT==LT_SINGULAR)
679        LoadResult = iiLibCmd(s, FALSE, FALSE,TRUE);
680      #ifdef HAVE_DYNAMIC_LOADING
681      else if ((LT==LT_ELF) || (LT==LT_HPUX))
682        LoadResult = load_modules(s,libnamebuf,FALSE);
683      #endif
684      else if (LT==LT_BUILTIN)
685      {
686        LoadResult=load_builtin(s,FALSE, iiGetBuiltinModInit(s));
687      }
688      if(!LoadResult )
689      {
690        v->name = iiConvName(libname);
691        break;
692      }
693    }
694  }
695  omFree(libname);
696  return LoadResult;
697}
698
699/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
700/* check, if library lib has already been loaded
701   if yes, writes filename of lib into where and returns TRUE,
702      no, returns FALSE
703*/
704BOOLEAN iiLocateLib(const char* lib, char* where)
705{
706  char *plib = iiConvName(lib);
707  idhdl pl = basePack->idroot->get(plib,0);
708  if( (pl!=NULL) && (IDTYP(pl)==PACKAGE_CMD) &&
709    (IDPACKAGE(pl)->language == LANG_SINGULAR))
710  {
711    strncpy(where,IDPACKAGE(pl)->libname,127);
712    return TRUE;
713  }
714  else
715    return FALSE;;
716}
717
718BOOLEAN iiLibCmd( char *newlib, BOOLEAN autoexport, BOOLEAN tellerror, BOOLEAN force )
719{
720  char libnamebuf[128];
721  // procinfov pi;
722  // idhdl h;
723  idhdl pl;
724  // idhdl hl;
725  // long pos = 0L;
726  char *plib = iiConvName(newlib);
727  FILE * fp = feFopen( newlib, "r", libnamebuf, tellerror );
728  // int lines = 1;
729  BOOLEAN LoadResult = TRUE;
730
731  if (fp==NULL)
732  {
733    return TRUE;
734  }
735  pl = basePack->idroot->get(plib,0);
736  if (pl==NULL)
737  {
738    pl = enterid( plib,0, PACKAGE_CMD,
739                  &(basePack->idroot), TRUE );
740    IDPACKAGE(pl)->language = LANG_SINGULAR;
741    IDPACKAGE(pl)->libname=omStrDup(newlib);
742  }
743  else
744  {
745    if(IDTYP(pl)!=PACKAGE_CMD)
746    {
747      WarnS("not of type package.");
748      fclose(fp);
749      return TRUE;
750    }
751    if (!force) return FALSE;
752  }
753  LoadResult = iiLoadLIB(fp, libnamebuf, newlib, pl, autoexport, tellerror);
754  omFree((ADDRESS)newlib);
755
756  if(!LoadResult) IDPACKAGE(pl)->loaded = TRUE;
757  omFree((ADDRESS)plib);
758
759 return LoadResult;
760}
761/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
762static void iiCleanProcs(idhdl &root)
763{
764  idhdl prev=NULL;
765  loop
766  {
767    if (root==NULL) return;
768    if (IDTYP(root)==PROC_CMD)
769    {
770      procinfo *pi=(procinfo*)IDDATA(root);
771      if ((pi->language == LANG_SINGULAR)
772      && (pi->data.s.body_start == 0L))
773      {
774        // procinfo data incorrect:
775        // - no proc body can start at the beginning of the file
776        killhdl(root);
777        if (prev==NULL)
778          root=IDROOT;
779        else
780        {
781          root=prev;
782          prev=NULL;
783        }
784        continue;
785      }
786    }
787    prev=root;
788    root=IDNEXT(root);
789  }
790}
791static void iiRunInit(package p)
792{
793  idhdl h=p->idroot->get("mod_init",0);
794  if (h==NULL) return;
795  if (IDTYP(h)==PROC_CMD)
796  {
797    int save=yylineno;
798    myynest++;
799    // procinfo *pi=(procinfo*)IDDATA(h);
800    //PrintS("mod_init found\n");
801    iiMake_proc(h,p,NULL);
802    myynest--;
803    yylineno=save;
804  }
805}
806/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
807BOOLEAN iiLoadLIB(FILE *fp, const char *libnamebuf, const char*newlib,
808             idhdl pl, BOOLEAN autoexport, BOOLEAN tellerror)
809{
810  extern FILE *yylpin;
811  libstackv ls_start = library_stack;
812  lib_style_types lib_style;
813
814  yylpin = fp;
815  #if YYLPDEBUG > 1
816  print_init();
817  #endif
818  extern int lpverbose;
819  if (BVERBOSE(V_DEBUG_LIB)) lpverbose=1;
820  else lpverbose=0;
821  // yylplex sets also text_buffer
822  if (text_buffer!=NULL) *text_buffer='\0';
823  yylplex(newlib, libnamebuf, &lib_style, pl, autoexport);
824  if(yylp_errno)
825  {
826    Werror("Library %s: ERROR occurred: in line %d, %d.", newlib, yylplineno,
827         current_pos(0));
828    if(yylp_errno==YYLP_BAD_CHAR)
829    {
830      Werror(yylp_errlist[yylp_errno], *text_buffer, yylplineno);
831      omFree((ADDRESS)text_buffer);
832      text_buffer=NULL;
833    }
834    else
835      Werror(yylp_errlist[yylp_errno], yylplineno);
836    WerrorS("Cannot load library,... aborting.");
837    reinit_yylp();
838    fclose( yylpin );
839    iiCleanProcs(IDROOT);
840    return TRUE;
841  }
842  if (BVERBOSE(V_LOAD_LIB))
843    Print( "// ** loaded %s %s\n", libnamebuf, text_buffer);
844  if( (lib_style == OLD_LIBSTYLE) && (BVERBOSE(V_LOAD_LIB)))
845  {
846    Warn( "library %s has old format. This format is still accepted,", newlib);
847    Warn( "but for functionality you may wish to change to the new");
848    Warn( "format. Please refer to the manual for further information.");
849  }
850  reinit_yylp();
851  fclose( yylpin );
852  fp = NULL;
853  iiRunInit(IDPACKAGE(pl));
854
855  {
856    libstackv ls;
857    for(ls = library_stack; (ls != NULL) && (ls != ls_start); )
858    {
859      if(ls->to_be_done)
860      {
861        ls->to_be_done=FALSE;
862        iiLibCmd(ls->get(),autoexport,tellerror,FALSE);
863        ls = ls->pop(newlib);
864      }
865    }
866#if 0
867    PrintS("--------------------\n");
868    for(ls = library_stack; ls != NULL; ls = ls->next)
869    {
870      Print("%s: LIB-stack:(%d), %s %s\n", newlib, ls->cnt, ls->get(),
871        ls->to_be_done ? "not loaded" : "loaded");
872    }
873    PrintS("--------------------\n");
874#endif
875  }
876
877  if(fp != NULL) fclose(fp);
878  return FALSE;
879}
880
881
882/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
883procinfo *iiInitSingularProcinfo(procinfov pi, const char *libname,
884              const char *procname, int, long pos, BOOLEAN pstatic)
885{
886  memset(pi,0,sizeof(*pi));
887  pi->libname = omStrDup(libname);
888  pi->procname = omStrDup(procname);
889  pi->language = LANG_SINGULAR;
890  pi->ref = 1;
891  pi->is_static = pstatic;
892  pi->data.s.proc_start = pos;
893  return(pi);
894}
895
896/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
897int iiAddCproc(const char *libname, const char *procname, BOOLEAN pstatic,
898               BOOLEAN(*func)(leftv res, leftv v))
899{
900  procinfov pi;
901  idhdl h;
902
903  #ifndef SING_NDEBUG
904  int dummy;
905  if (IsCmd(procname,dummy))
906  {
907    Werror(">>%s< is a reserved name",procname);
908    return 0;
909  }
910  #endif
911
912  h=IDROOT->get(procname,0);
913  if ((h!=NULL)
914  && (IDTYP(h)==PROC_CMD))
915  {
916    pi = IDPROC(h);
917    if ((pi->language == LANG_SINGULAR)
918    &&(BVERBOSE(V_REDEFINE)))
919      Warn("extend `%s`",procname);
920  }
921  else
922  {
923    h = enterid(procname,0, PROC_CMD, &IDROOT, TRUE);
924  }
925  if ( h!= NULL )
926  {
927    pi = IDPROC(h);
928    if((pi->language == LANG_SINGULAR)
929    ||(pi->language == LANG_NONE))
930    {
931      omfree(pi->libname);
932      pi->libname = omStrDup(libname);
933      omfree(pi->procname);
934      pi->procname = omStrDup(procname);
935      pi->language = LANG_C;
936      pi->ref = 1;
937      pi->is_static = pstatic;
938      pi->data.o.function = func;
939    }
940    else if(pi->language == LANG_C)
941    {
942      if(pi->data.o.function == func)
943      {
944        pi->ref++;
945      }
946      else
947      {
948        omfree(pi->libname);
949        pi->libname = omStrDup(libname);
950        omfree(pi->procname);
951        pi->procname = omStrDup(procname);
952        pi->language = LANG_C;
953        pi->ref = 1;
954        pi->is_static = pstatic;
955        pi->data.o.function = func;
956      }
957    }
958    else
959      Warn("internal error: unknown procedure type %d",pi->language);
960    return(1);
961  }
962  else
963  {
964    WarnS("iiAddCproc: failed.");
965  }
966  return(0);
967}
968
969int iiAddCprocTop(const char *libname, const char *procname, BOOLEAN pstatic,
970               BOOLEAN(*func)(leftv res, leftv v))
971{
972  int r=iiAddCproc(libname,procname,pstatic,func);
973  package s=currPack;
974  currPack=basePack;
975  if (r) r=iiAddCproc(libname,procname,pstatic,func);
976  currPack=s;
977  return r;
978}
979
980/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
981#ifdef HAVE_DYNAMIC_LOADING
982BOOLEAN load_modules(const char *newlib, char *fullname, BOOLEAN autoexport)
983{
984#ifdef HAVE_STATIC
985  WerrorS("mod_init: static version can not load modules");
986  return TRUE;
987#else
988/*
989  typedef int (*fktn_t)(int(*iiAddCproc)(const char *libname, const char *procname,
990                               BOOLEAN pstatic,
991                               BOOLEAN(*func)(leftv res, leftv v)));
992*/
993  SModulFunc_t fktn;
994  idhdl pl;
995  char *plib = iiConvName(newlib);
996  BOOLEAN RET=TRUE;
997  int token;
998  char FullName[256];
999
1000  memset(FullName,0,256);
1001
1002  if( *fullname != '/' &&  *fullname != '.' )
1003    sprintf(FullName, "./%s", newlib);
1004  else strncpy(FullName, fullname,255);
1005
1006
1007  if(IsCmd(plib, token))
1008  {
1009    Werror("'%s' is resered identifier\n", plib);
1010    goto load_modules_end;
1011  }
1012  pl = basePack->idroot->get(plib,0); /* packages only in top level
1013                                        (see enterid) */
1014  if ((pl!=NULL)
1015  &&(IDTYP(pl)==PACKAGE_CMD))
1016  {
1017    if(IDPACKAGE(pl)->language==LANG_C)
1018    {
1019      if (BVERBOSE(V_LOAD_LIB)) Warn( "%s already loaded as package", newlib);
1020      omFree(plib);
1021      return FALSE;
1022    }
1023  }
1024  else
1025  {
1026    pl = enterid( plib,0, PACKAGE_CMD, &IDROOT, TRUE );
1027    IDPACKAGE(pl)->libname=omStrDup(newlib);
1028  }
1029  IDPACKAGE(pl)->language = LANG_C;
1030  if (dynl_check_opened(FullName))
1031  {
1032    if (BVERBOSE(V_LOAD_LIB)) Warn( "%s already loaded as C library", fullname);
1033    return FALSE;
1034  }
1035  if((IDPACKAGE(pl)->handle=dynl_open(FullName))==(void *)NULL)
1036  {
1037    Werror("dynl_open failed:%s", dynl_error());
1038    Werror("%s not found", newlib);
1039    killhdl2(pl,&(basePack->idroot),NULL); // remove package
1040    goto load_modules_end;
1041  }
1042  else
1043  {
1044    SModulFunctions sModulFunctions;
1045
1046    package s=currPack;
1047    currPack=IDPACKAGE(pl);
1048    fktn = (SModulFunc_t)dynl_sym(IDPACKAGE(pl)->handle, "mod_init");
1049    if( fktn!= NULL)
1050    {
1051      sModulFunctions.iiArithAddCmd = iiArithAddCmd;
1052      if (autoexport) sModulFunctions.iiAddCproc = iiAddCprocTop;
1053      else            sModulFunctions.iiAddCproc = iiAddCproc;
1054      int ver=(*fktn)(&sModulFunctions);
1055      if (ver==MAX_TOK)
1056      {
1057        if (BVERBOSE(V_LOAD_LIB)) Print( "// ** loaded %s\n", fullname);
1058      }
1059      else
1060      {
1061        Warn("loaded %s for a different version of Singular(expected MAX_TOK: %d, got %d)",fullname,MAX_TOK,ver);
1062      }
1063      currPack->loaded=1;
1064      currPack=s;
1065      RET=FALSE;
1066    }
1067    else
1068    {
1069      Werror("mod_init not found:: %s\nThis is probably not a dynamic module for Singular!\n", dynl_error());
1070      killhdl2(pl,&(basePack->idroot),NULL); // remove package
1071    }
1072  }
1073
1074  load_modules_end:
1075  return RET;
1076#endif /*STATIC */
1077}
1078#endif /* HAVE_DYNAMIC_LOADING */
1079/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
1080BOOLEAN load_builtin(const char *newlib, BOOLEAN autoexport, SModulFunc_t init)
1081{
1082  int iiAddCproc(const char *libname, const char *procname, BOOLEAN pstatic,
1083                 BOOLEAN(*func)(leftv res, leftv v));
1084/*
1085  typedef int (*fktn_t)(int(*iiAddCproc)(const char *libname, const char *procname,
1086                               BOOLEAN pstatic,
1087                               BOOLEAN(*func)(leftv res, leftv v)));
1088*/
1089  // SModulFunc_t fktn;
1090  idhdl pl;
1091  char *plib = iiConvName(newlib);
1092  // BOOLEAN RET=TRUE;
1093  // int token;
1094
1095  pl = basePack->idroot->get(plib,0); // search PACKAGE only in Top
1096  if ((pl!=NULL)
1097  &&(IDTYP(pl)==PACKAGE_CMD))
1098  {
1099    if(IDPACKAGE(pl)->language==LANG_C)
1100    {
1101      if (BVERBOSE(V_LOAD_LIB)) Warn( "(builtin) %s already loaded", newlib);
1102      omFree(plib);
1103      return FALSE;
1104    }
1105  }
1106  else
1107  {
1108    pl = enterid( plib,0, PACKAGE_CMD, &IDROOT, TRUE );
1109    IDPACKAGE(pl)->libname=omStrDup(newlib);
1110  }
1111  IDPACKAGE(pl)->language = LANG_C;
1112
1113  IDPACKAGE(pl)->handle=(void *)NULL;
1114  SModulFunctions sModulFunctions;
1115
1116  package s=currPack;
1117  currPack=IDPACKAGE(pl);
1118  if( init!= NULL)
1119  {
1120    sModulFunctions.iiArithAddCmd = iiArithAddCmd;
1121    if (autoexport) sModulFunctions.iiAddCproc = iiAddCprocTop;
1122    else            sModulFunctions.iiAddCproc = iiAddCproc;
1123    (*init)(&sModulFunctions);
1124  }
1125  if (BVERBOSE(V_LOAD_LIB)) Print( "// ** loaded (builtin) %s \n", newlib);
1126  currPack->loaded=1;
1127  currPack=s;
1128
1129  return FALSE;
1130}
1131/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
1132void module_help_main(const char *newlib,const char *help)
1133{
1134  char *plib = iiConvName(newlib);
1135  idhdl pl = basePack->idroot->get(plib,0);
1136  if ((pl==NULL)||(IDTYP(pl)!=PACKAGE_CMD))
1137    Werror(">>%s<< is not a package (trying to add package help)",plib);
1138  else
1139  {
1140    package s=currPack;
1141    currPack=IDPACKAGE(pl);
1142    idhdl h=enterid(omStrDup("info"),0,STRING_CMD,&IDROOT,FALSE);
1143    IDSTRING(h)=omStrDup(help);
1144    currPack=s;
1145  }
1146}
1147void module_help_proc(const char *newlib,const char *p, const char *help)
1148{
1149  char *plib = iiConvName(newlib);
1150  idhdl pl = basePack->idroot->get(plib,0);
1151  if ((pl==NULL)||(IDTYP(pl)!=PACKAGE_CMD))
1152    Werror(">>%s<< is not a package(trying to add help for %s)",plib,p);
1153  else
1154  {
1155    package s=currPack;
1156    currPack=IDPACKAGE(pl);
1157    char buff[256];
1158    buff[255]='\0';
1159    strncpy(buff,p,255);
1160    strncat(buff,"_help",255-strlen(p));
1161    idhdl h=enterid(omStrDup(buff),0,STRING_CMD,&IDROOT,FALSE);
1162    IDSTRING(h)=omStrDup(help);
1163    currPack=s;
1164  }
1165}
1166/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
1167
1168#ifdef HAVE_DYNAMIC_LOADING
1169// loads a dynamic module from the binary path and returns a named function
1170// returns NULL, if something fails
1171void* binary_module_function(const char* newlib, const char* funcname)
1172{
1173  void* result = NULL;
1174
1175  const char* bin_dir = feGetResource('b');
1176  if (!bin_dir)  { return NULL; }
1177
1178  char path_name[MAXPATHLEN];
1179  sprintf(path_name, "%s%s%s.%s", bin_dir, DIR_SEPP, newlib, MODULE_SUFFIX_STRING);
1180
1181  void* openlib = dynl_open(path_name);
1182  if(!openlib)
1183  {
1184    Werror("dynl_open of %s failed:%s", path_name, dynl_error());
1185    return NULL;
1186  }
1187  result = dynl_sym(openlib, funcname);
1188  if (!result) Werror("%s: %s\n", funcname, dynl_error());
1189
1190  return result;
1191}
1192#endif
1193
1194/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
1195char mytoupper(char c)
1196{
1197  if(c>=97 && c<=(97+26)) c-=32;
1198  return(c);
1199}
1200
1201char mytolower(char c)
1202{
1203  if(c>=65 && c<=(65+26)) c+=32;
1204  return(c);
1205}
1206
1207/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
1208//#if defined(WINNT)
1209//#  define  FS_SEP '\\'
1210//#else
1211//#  define FS_SEP '/'
1212//#endif
1213
1214char *iiConvName(const char *libname)
1215{
1216  char *tmpname = omStrDup(libname);
1217  char *p = strrchr(tmpname, DIR_SEP);
1218  char *r;
1219  if(p==NULL) p = tmpname;
1220  else p++;
1221  r = (char *)strchr(p, '.');
1222  if( r!= NULL) *r = '\0';
1223  r = omStrDup(p);
1224  *r = mytoupper(*r);
1225  // printf("iiConvName: '%s' '%s' => '%s'\n", libname, tmpname, r);
1226  omFree((ADDRESS)tmpname);
1227
1228  return(r);
1229}
1230
1231/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
1232#if 0 /* debug only */
1233void piShowProcList()
1234{
1235  idhdl h;
1236  procinfo *proc;
1237  char *name;
1238
1239  Print( "%-15s  %20s      %s,%s  %s,%s   %s,%s\n", "Library", "function",
1240         "line", "start", "line", "body", "line", "example");
1241  for(h = IDROOT; h != NULL; h = IDNEXT(h))
1242  {
1243    if(IDTYP(h) == PROC_CMD)
1244    {
1245      proc = IDPROC(h);
1246      if(strcmp(proc->procname, IDID(h))!=0)
1247      {
1248        name = (char *)omAlloc(strlen(IDID(h))+strlen(proc->procname)+4);
1249        sprintf(name, "%s -> %s", IDID(h), proc->procname);
1250        Print( "%d %-15s  %20s ", proc->is_static ? 1 : 0, proc->libname, name);
1251        omFree((ADDRESS)name);
1252      }
1253      else
1254        Print( "%d %-15s  %20s ", proc->is_static ? 1 : 0, proc->libname,
1255               proc->procname);
1256      if(proc->language==LANG_SINGULAR)
1257        Print("line %-5ld  %4d,%-5ld  %4d,%-5ld\n",
1258              proc->data.s.proc_start,
1259              proc->data.s.body_lineno, proc->data.s.body_start,
1260              proc->data.s.example_lineno, proc->data.s.example_start);
1261      else if(proc->language==LANG_C)
1262        PrintS("type: object\n");
1263    }
1264  }
1265}
1266#endif
1267
1268/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
1269//char *iiLineNo(char *procname, int lineno)
1270//{
1271//  char buf[256];
1272//  idhdl pn = ggetid(procname);
1273//  procinfo *pi = IDPROC(pn);
1274//
1275//  sprintf(buf, "%s %3d\0", procname, lineno);
1276//  //sprintf(buf, "%s::%s %3d\0", pi->libname, pi->procname,
1277//  //  lineno + pi->data.s.body_lineno);
1278//  return(buf);
1279//}
1280/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
1281#ifdef HAVE_LIBPARSER
1282void libstack::push(const char */*p*/, char *libn)
1283{
1284  libstackv lp;
1285  if( !iiGetLibStatus(libn))
1286  {
1287    for(lp = this;lp!=NULL;lp=lp->next)
1288    {
1289      if(strcmp(lp->get(), libn)==0) break;
1290    }
1291    if(lp==NULL)
1292    {
1293      libstackv ls = (libstack *)omAlloc0Bin(libstack_bin);
1294      ls->next = this;
1295      ls->libname = omStrDup(libn);
1296      ls->to_be_done = TRUE;
1297      if(this != NULL) ls->cnt = this->cnt+1; else ls->cnt = 0;
1298      library_stack = ls;
1299    }
1300  }
1301}
1302
1303libstackv libstack::pop(const char */*p*/)
1304{
1305  libstackv ls = this;
1306  //omFree((ADDRESS)ls->libname);
1307  library_stack = ls->next;
1308  omFreeBin((ADDRESS)ls,  libstack_bin);
1309  return(library_stack);
1310}
1311
1312#endif /* HAVE_LIBPARSER */
1313/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
Note: See TracBrowser for help on using the repository browser.