ports.c 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222
  1. /* Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004,
  2. * 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public License
  6. * as published by the Free Software Foundation; either version 3 of
  7. * the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  17. * 02110-1301 USA
  18. */
  19. /* Headers. */
  20. #define _LARGEFILE64_SOURCE /* ask for stat64 etc */
  21. #ifdef HAVE_CONFIG_H
  22. # include <config.h>
  23. #endif
  24. #include <stdio.h>
  25. #include <errno.h>
  26. #include <fcntl.h> /* for chsize on mingw */
  27. #include <assert.h>
  28. #include <iconv.h>
  29. #include <uniconv.h>
  30. #include <unistr.h>
  31. #include <striconveh.h>
  32. #include <assert.h>
  33. #include "libguile/_scm.h"
  34. #include "libguile/async.h"
  35. #include "libguile/deprecation.h"
  36. #include "libguile/eval.h"
  37. #include "libguile/fports.h" /* direct access for seek and truncate */
  38. #include "libguile/goops.h"
  39. #include "libguile/smob.h"
  40. #include "libguile/chars.h"
  41. #include "libguile/dynwind.h"
  42. #include "libguile/keywords.h"
  43. #include "libguile/hashtab.h"
  44. #include "libguile/root.h"
  45. #include "libguile/strings.h"
  46. #include "libguile/mallocs.h"
  47. #include "libguile/validate.h"
  48. #include "libguile/ports.h"
  49. #include "libguile/ports-internal.h"
  50. #include "libguile/vectors.h"
  51. #include "libguile/weak-set.h"
  52. #include "libguile/fluids.h"
  53. #include "libguile/eq.h"
  54. #include "libguile/alist.h"
  55. #ifdef HAVE_STRING_H
  56. #include <string.h>
  57. #endif
  58. #ifdef HAVE_IO_H
  59. #include <io.h>
  60. #endif
  61. #ifdef HAVE_UNISTD_H
  62. #include <unistd.h>
  63. #endif
  64. #ifdef HAVE_SYS_IOCTL_H
  65. #include <sys/ioctl.h>
  66. #endif
  67. /* Mingw (version 3.4.5, circa 2006) has ftruncate as an alias for chsize
  68. already, but have this code here in case that wasn't so in past versions,
  69. or perhaps to help other minimal DOS environments.
  70. gnulib ftruncate.c has code using fcntl F_CHSIZE and F_FREESP, which
  71. might be possibilities if we've got other systems without ftruncate. */
  72. #if defined HAVE_CHSIZE && ! defined HAVE_FTRUNCATE
  73. #define ftruncate(fd, size) chsize (fd, size)
  74. #undef HAVE_FTRUNCATE
  75. #define HAVE_FTRUNCATE 1
  76. #endif
  77. /* Port encodings are case-insensitive ASCII strings. */
  78. static char
  79. ascii_toupper (char c)
  80. {
  81. return (c < 'a' || c > 'z') ? c : ('A' + (c - 'a'));
  82. }
  83. /* It is only necessary to use this function on encodings that come from
  84. the user and have not been canonicalized yet. Encodings that are set
  85. on ports or in the default encoding fluid are in upper-case, and can
  86. be compared with strcmp. */
  87. static int
  88. encoding_matches (const char *enc, const char *upper)
  89. {
  90. if (!enc)
  91. enc = "ISO-8859-1";
  92. while (*enc)
  93. if (ascii_toupper (*enc++) != *upper++)
  94. return 0;
  95. return !*upper;
  96. }
  97. static char*
  98. canonicalize_encoding (const char *enc)
  99. {
  100. char *ret;
  101. int i;
  102. if (!enc)
  103. return "ISO-8859-1";
  104. ret = scm_gc_strdup (enc, "port");
  105. for (i = 0; ret[i]; i++)
  106. {
  107. if (ret[i] > 127)
  108. /* Restrict to ASCII. */
  109. scm_misc_error (NULL, "invalid character encoding ~s",
  110. scm_list_1 (scm_from_latin1_string (enc)));
  111. else
  112. ret[i] = ascii_toupper (ret[i]);
  113. }
  114. return ret;
  115. }
  116. /* The port kind table --- a dynamically resized array of port types. */
  117. /* scm_ptobs scm_numptob
  118. * implement a dynamically resized array of ptob records.
  119. * Indexes into this table are used when generating type
  120. * tags for smobjects (if you know a tag you can get an index and conversely).
  121. */
  122. static scm_t_ptob_descriptor **scm_ptobs = NULL;
  123. static long scm_numptob = 0; /* Number of port types. */
  124. static long scm_ptobs_size = 0; /* Number of slots in the port type
  125. table. */
  126. static scm_i_pthread_mutex_t scm_ptobs_lock = SCM_I_PTHREAD_MUTEX_INITIALIZER;
  127. long
  128. scm_c_num_port_types (void)
  129. {
  130. long ret;
  131. scm_i_pthread_mutex_lock (&scm_ptobs_lock);
  132. ret = scm_numptob;
  133. scm_i_pthread_mutex_unlock (&scm_ptobs_lock);
  134. return ret;
  135. }
  136. scm_t_ptob_descriptor*
  137. scm_c_port_type_ref (long ptobnum)
  138. {
  139. scm_t_ptob_descriptor *ret = NULL;
  140. scm_i_pthread_mutex_lock (&scm_ptobs_lock);
  141. if (0 <= ptobnum && ptobnum < scm_numptob)
  142. ret = scm_ptobs[ptobnum];
  143. scm_i_pthread_mutex_unlock (&scm_ptobs_lock);
  144. if (!ret)
  145. scm_out_of_range ("scm_c_port_type_ref", scm_from_long (ptobnum));
  146. return ret;
  147. }
  148. long
  149. scm_c_port_type_add_x (scm_t_ptob_descriptor *desc)
  150. {
  151. long ret = -1;
  152. scm_i_pthread_mutex_lock (&scm_ptobs_lock);
  153. if (scm_numptob + 1 < SCM_I_MAX_PORT_TYPE_COUNT)
  154. {
  155. if (scm_numptob == scm_ptobs_size)
  156. {
  157. unsigned long old_size = scm_ptobs_size;
  158. scm_t_ptob_descriptor **old_ptobs = scm_ptobs;
  159. /* Currently there are only 9 predefined port types, so one
  160. resize will cover it. */
  161. scm_ptobs_size = old_size + 10;
  162. if (scm_ptobs_size >= SCM_I_MAX_PORT_TYPE_COUNT)
  163. scm_ptobs_size = SCM_I_MAX_PORT_TYPE_COUNT;
  164. scm_ptobs = scm_gc_malloc (sizeof (*scm_ptobs) * scm_ptobs_size,
  165. "scm_ptobs");
  166. memcpy (scm_ptobs, old_ptobs, sizeof (*scm_ptobs) * scm_numptob);
  167. }
  168. ret = scm_numptob++;
  169. scm_ptobs[ret] = desc;
  170. }
  171. scm_i_pthread_mutex_unlock (&scm_ptobs_lock);
  172. if (ret < 0)
  173. scm_out_of_range ("scm_c_port_type_add_x", scm_from_long (scm_numptob));
  174. return ret;
  175. }
  176. /*
  177. * We choose to use an interface similar to the smob interface with
  178. * fill_input and write as standard fields, passed to the port
  179. * type constructor, and optional fields set by setters.
  180. */
  181. static void
  182. flush_port_default (SCM port SCM_UNUSED)
  183. {
  184. }
  185. static void
  186. end_input_default (SCM port SCM_UNUSED, int offset SCM_UNUSED)
  187. {
  188. }
  189. scm_t_bits
  190. scm_make_port_type (char *name,
  191. int (*fill_input) (SCM port),
  192. void (*write) (SCM port, const void *data, size_t size))
  193. {
  194. scm_t_ptob_descriptor *desc;
  195. long ptobnum;
  196. desc = scm_gc_malloc_pointerless (sizeof (*desc), "port-type");
  197. memset (desc, 0, sizeof (*desc));
  198. desc->name = name;
  199. desc->print = scm_port_print;
  200. desc->write = write;
  201. desc->flush = flush_port_default;
  202. desc->end_input = end_input_default;
  203. desc->fill_input = fill_input;
  204. ptobnum = scm_c_port_type_add_x (desc);
  205. /* Make a class object if GOOPS is present. */
  206. if (SCM_UNPACK (scm_port_class[0]) != 0)
  207. scm_make_port_classes (ptobnum, name);
  208. return scm_tc7_port + ptobnum * 256;
  209. }
  210. void
  211. scm_set_port_mark (scm_t_bits tc, SCM (*mark) (SCM))
  212. {
  213. scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->mark = mark;
  214. }
  215. void
  216. scm_set_port_free (scm_t_bits tc, size_t (*free) (SCM))
  217. {
  218. scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->free = free;
  219. }
  220. void
  221. scm_set_port_print (scm_t_bits tc, int (*print) (SCM exp, SCM port,
  222. scm_print_state *pstate))
  223. {
  224. scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->print = print;
  225. }
  226. void
  227. scm_set_port_equalp (scm_t_bits tc, SCM (*equalp) (SCM, SCM))
  228. {
  229. scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->equalp = equalp;
  230. }
  231. void
  232. scm_set_port_close (scm_t_bits tc, int (*close) (SCM))
  233. {
  234. scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->close = close;
  235. }
  236. void
  237. scm_set_port_flush (scm_t_bits tc, void (*flush) (SCM port))
  238. {
  239. scm_t_ptob_descriptor *ptob = scm_c_port_type_ref (SCM_TC2PTOBNUM (tc));
  240. ptob->flush = flush;
  241. ptob->flags |= SCM_PORT_TYPE_HAS_FLUSH;
  242. }
  243. void
  244. scm_set_port_end_input (scm_t_bits tc, void (*end_input) (SCM port, int offset))
  245. {
  246. scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->end_input = end_input;
  247. }
  248. void
  249. scm_set_port_seek (scm_t_bits tc, scm_t_off (*seek) (SCM, scm_t_off, int))
  250. {
  251. scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->seek = seek;
  252. }
  253. void
  254. scm_set_port_truncate (scm_t_bits tc, void (*truncate) (SCM, scm_t_off))
  255. {
  256. scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->truncate = truncate;
  257. }
  258. void
  259. scm_set_port_input_waiting (scm_t_bits tc, int (*input_waiting) (SCM))
  260. {
  261. scm_c_port_type_ref (SCM_TC2PTOBNUM (tc))->input_waiting = input_waiting;
  262. }
  263. static void
  264. scm_i_set_pending_eof (SCM port)
  265. {
  266. SCM_PORT_GET_INTERNAL (port)->pending_eof = 1;
  267. }
  268. static void
  269. scm_i_clear_pending_eof (SCM port)
  270. {
  271. SCM_PORT_GET_INTERNAL (port)->pending_eof = 0;
  272. }
  273. SCM_DEFINE (scm_i_port_property, "%port-property", 2, 0, 0,
  274. (SCM port, SCM key),
  275. "Return the property of @var{port} associated with @var{key}.")
  276. #define FUNC_NAME s_scm_i_port_property
  277. {
  278. scm_i_pthread_mutex_t *lock;
  279. SCM result;
  280. SCM_VALIDATE_OPPORT (1, port);
  281. scm_c_lock_port (port, &lock);
  282. result = scm_assq_ref (SCM_PORT_GET_INTERNAL (port)->alist, key);
  283. if (lock)
  284. scm_i_pthread_mutex_unlock (lock);
  285. return result;
  286. }
  287. #undef FUNC_NAME
  288. SCM_DEFINE (scm_i_set_port_property_x, "%set-port-property!", 3, 0, 0,
  289. (SCM port, SCM key, SCM value),
  290. "Set the property of @var{port} associated with @var{key} to @var{value}.")
  291. #define FUNC_NAME s_scm_i_set_port_property_x
  292. {
  293. scm_i_pthread_mutex_t *lock;
  294. scm_t_port_internal *pti;
  295. SCM_VALIDATE_OPPORT (1, port);
  296. scm_c_lock_port (port, &lock);
  297. pti = SCM_PORT_GET_INTERNAL (port);
  298. pti->alist = scm_assq_set_x (pti->alist, key, value);
  299. if (lock)
  300. scm_i_pthread_mutex_unlock (lock);
  301. return SCM_UNSPECIFIED;
  302. }
  303. #undef FUNC_NAME
  304. /* Standard ports --- current input, output, error, and more(!). */
  305. static SCM cur_inport_fluid = SCM_BOOL_F;
  306. static SCM cur_outport_fluid = SCM_BOOL_F;
  307. static SCM cur_errport_fluid = SCM_BOOL_F;
  308. static SCM cur_loadport_fluid = SCM_BOOL_F;
  309. SCM_DEFINE (scm_current_input_port, "current-input-port", 0, 0, 0,
  310. (),
  311. "Return the current input port. This is the default port used\n"
  312. "by many input procedures. Initially, @code{current-input-port}\n"
  313. "returns the @dfn{standard input} in Unix and C terminology.")
  314. #define FUNC_NAME s_scm_current_input_port
  315. {
  316. if (scm_is_true (cur_inport_fluid))
  317. return scm_fluid_ref (cur_inport_fluid);
  318. else
  319. return SCM_BOOL_F;
  320. }
  321. #undef FUNC_NAME
  322. SCM_DEFINE (scm_current_output_port, "current-output-port", 0, 0, 0,
  323. (),
  324. "Return the current output port. This is the default port used\n"
  325. "by many output procedures. Initially,\n"
  326. "@code{current-output-port} returns the @dfn{standard output} in\n"
  327. "Unix and C terminology.")
  328. #define FUNC_NAME s_scm_current_output_port
  329. {
  330. if (scm_is_true (cur_outport_fluid))
  331. return scm_fluid_ref (cur_outport_fluid);
  332. else
  333. return SCM_BOOL_F;
  334. }
  335. #undef FUNC_NAME
  336. SCM_DEFINE (scm_current_error_port, "current-error-port", 0, 0, 0,
  337. (),
  338. "Return the port to which errors and warnings should be sent (the\n"
  339. "@dfn{standard error} in Unix and C terminology).")
  340. #define FUNC_NAME s_scm_current_error_port
  341. {
  342. if (scm_is_true (cur_errport_fluid))
  343. return scm_fluid_ref (cur_errport_fluid);
  344. else
  345. return SCM_BOOL_F;
  346. }
  347. #undef FUNC_NAME
  348. SCM
  349. scm_current_warning_port (void)
  350. {
  351. static SCM cwp_var = SCM_UNDEFINED;
  352. static scm_i_pthread_mutex_t cwp_var_mutex
  353. = SCM_I_PTHREAD_MUTEX_INITIALIZER;
  354. scm_i_scm_pthread_mutex_lock (&cwp_var_mutex);
  355. if (SCM_UNBNDP (cwp_var))
  356. cwp_var = scm_c_private_variable ("guile", "current-warning-port");
  357. scm_i_pthread_mutex_unlock (&cwp_var_mutex);
  358. return scm_call_0 (scm_variable_ref (cwp_var));
  359. }
  360. SCM_DEFINE (scm_current_load_port, "current-load-port", 0, 0, 0,
  361. (),
  362. "Return the current-load-port.\n"
  363. "The load port is used internally by @code{primitive-load}.")
  364. #define FUNC_NAME s_scm_current_load_port
  365. {
  366. return scm_fluid_ref (cur_loadport_fluid);
  367. }
  368. #undef FUNC_NAME
  369. SCM_DEFINE (scm_set_current_input_port, "set-current-input-port", 1, 0, 0,
  370. (SCM port),
  371. "@deffnx {Scheme Procedure} set-current-output-port port\n"
  372. "@deffnx {Scheme Procedure} set-current-error-port port\n"
  373. "Change the ports returned by @code{current-input-port},\n"
  374. "@code{current-output-port} and @code{current-error-port}, respectively,\n"
  375. "so that they use the supplied @var{port} for input or output.")
  376. #define FUNC_NAME s_scm_set_current_input_port
  377. {
  378. SCM oinp = scm_fluid_ref (cur_inport_fluid);
  379. SCM_VALIDATE_OPINPORT (1, port);
  380. scm_fluid_set_x (cur_inport_fluid, port);
  381. return oinp;
  382. }
  383. #undef FUNC_NAME
  384. SCM_DEFINE (scm_set_current_output_port, "set-current-output-port", 1, 0, 0,
  385. (SCM port),
  386. "Set the current default output port to @var{port}.")
  387. #define FUNC_NAME s_scm_set_current_output_port
  388. {
  389. SCM ooutp = scm_fluid_ref (cur_outport_fluid);
  390. port = SCM_COERCE_OUTPORT (port);
  391. SCM_VALIDATE_OPOUTPORT (1, port);
  392. scm_fluid_set_x (cur_outport_fluid, port);
  393. return ooutp;
  394. }
  395. #undef FUNC_NAME
  396. SCM_DEFINE (scm_set_current_error_port, "set-current-error-port", 1, 0, 0,
  397. (SCM port),
  398. "Set the current default error port to @var{port}.")
  399. #define FUNC_NAME s_scm_set_current_error_port
  400. {
  401. SCM oerrp = scm_fluid_ref (cur_errport_fluid);
  402. port = SCM_COERCE_OUTPORT (port);
  403. SCM_VALIDATE_OPOUTPORT (1, port);
  404. scm_fluid_set_x (cur_errport_fluid, port);
  405. return oerrp;
  406. }
  407. #undef FUNC_NAME
  408. SCM
  409. scm_set_current_warning_port (SCM port)
  410. {
  411. static SCM cwp_var = SCM_BOOL_F;
  412. if (scm_is_false (cwp_var))
  413. cwp_var = scm_c_private_lookup ("guile", "current-warning-port");
  414. return scm_call_1 (scm_variable_ref (cwp_var), port);
  415. }
  416. void
  417. scm_dynwind_current_input_port (SCM port)
  418. #define FUNC_NAME NULL
  419. {
  420. SCM_VALIDATE_OPINPORT (1, port);
  421. scm_dynwind_fluid (cur_inport_fluid, port);
  422. }
  423. #undef FUNC_NAME
  424. void
  425. scm_dynwind_current_output_port (SCM port)
  426. #define FUNC_NAME NULL
  427. {
  428. port = SCM_COERCE_OUTPORT (port);
  429. SCM_VALIDATE_OPOUTPORT (1, port);
  430. scm_dynwind_fluid (cur_outport_fluid, port);
  431. }
  432. #undef FUNC_NAME
  433. void
  434. scm_dynwind_current_error_port (SCM port)
  435. #define FUNC_NAME NULL
  436. {
  437. port = SCM_COERCE_OUTPORT (port);
  438. SCM_VALIDATE_OPOUTPORT (1, port);
  439. scm_dynwind_fluid (cur_errport_fluid, port);
  440. }
  441. #undef FUNC_NAME
  442. void
  443. scm_i_dynwind_current_load_port (SCM port)
  444. {
  445. scm_dynwind_fluid (cur_loadport_fluid, port);
  446. }
  447. /* Retrieving a port's mode. */
  448. /* Return the flags that characterize a port based on the mode
  449. * string used to open a file for that port.
  450. *
  451. * See PORT FLAGS in scm.h
  452. */
  453. static long
  454. scm_i_mode_bits_n (SCM modes)
  455. {
  456. return (SCM_OPN
  457. | (scm_i_string_contains_char (modes, 'r')
  458. || scm_i_string_contains_char (modes, '+') ? SCM_RDNG : 0)
  459. | (scm_i_string_contains_char (modes, 'w')
  460. || scm_i_string_contains_char (modes, 'a')
  461. || scm_i_string_contains_char (modes, '+') ? SCM_WRTNG : 0)
  462. | (scm_i_string_contains_char (modes, '0') ? SCM_BUF0 : 0)
  463. | (scm_i_string_contains_char (modes, 'l') ? SCM_BUFLINE : 0));
  464. }
  465. long
  466. scm_mode_bits (char *modes)
  467. {
  468. /* Valid characters are rw+a0l. So, use latin1. */
  469. return scm_i_mode_bits (scm_from_latin1_string (modes));
  470. }
  471. long
  472. scm_i_mode_bits (SCM modes)
  473. {
  474. long bits;
  475. if (!scm_is_string (modes))
  476. scm_wrong_type_arg_msg (NULL, 0, modes, "string");
  477. bits = scm_i_mode_bits_n (modes);
  478. scm_remember_upto_here_1 (modes);
  479. return bits;
  480. }
  481. /* Return the mode flags from an open port.
  482. * Some modes such as "append" are only used when opening
  483. * a file and are not returned here. */
  484. SCM_DEFINE (scm_port_mode, "port-mode", 1, 0, 0,
  485. (SCM port),
  486. "Return the port modes associated with the open port @var{port}.\n"
  487. "These will not necessarily be identical to the modes used when\n"
  488. "the port was opened, since modes such as \"append\" which are\n"
  489. "used only during port creation are not retained.")
  490. #define FUNC_NAME s_scm_port_mode
  491. {
  492. char modes[4];
  493. modes[0] = '\0';
  494. port = SCM_COERCE_OUTPORT (port);
  495. SCM_VALIDATE_OPPORT (1, port);
  496. if (SCM_CELL_WORD_0 (port) & SCM_RDNG) {
  497. if (SCM_CELL_WORD_0 (port) & SCM_WRTNG)
  498. strcpy (modes, "r+");
  499. else
  500. strcpy (modes, "r");
  501. }
  502. else if (SCM_CELL_WORD_0 (port) & SCM_WRTNG)
  503. strcpy (modes, "w");
  504. if (SCM_CELL_WORD_0 (port) & SCM_BUF0)
  505. strcat (modes, "0");
  506. return scm_from_latin1_string (modes);
  507. }
  508. #undef FUNC_NAME
  509. /* The port table --- a weak set of all ports.
  510. We need a global registry of ports to flush them all at exit, and to
  511. get all the ports matching a file descriptor. */
  512. SCM scm_i_port_weak_set;
  513. /* Port finalization. */
  514. struct do_free_data
  515. {
  516. scm_t_ptob_descriptor *ptob;
  517. SCM port;
  518. };
  519. static SCM
  520. do_free (void *body_data)
  521. {
  522. struct do_free_data *data = body_data;
  523. /* `close' is for explicit `close-port' by user. `free' is for this
  524. purpose: ports collected by the GC. */
  525. data->ptob->free (data->port);
  526. return SCM_BOOL_T;
  527. }
  528. /* Finalize the object (a port) pointed to by PTR. */
  529. static void
  530. finalize_port (void *ptr, void *data)
  531. {
  532. SCM port = SCM_PACK_POINTER (ptr);
  533. if (!SCM_PORTP (port))
  534. abort ();
  535. if (SCM_OPENP (port))
  536. {
  537. struct do_free_data data;
  538. SCM_CLR_PORT_OPEN_FLAG (port);
  539. data.ptob = SCM_PORT_DESCRIPTOR (port);
  540. data.port = port;
  541. scm_internal_catch (SCM_BOOL_T, do_free, &data,
  542. scm_handle_by_message_noexit, NULL);
  543. scm_gc_ports_collected++;
  544. }
  545. }
  546. SCM
  547. scm_c_make_port_with_encoding (scm_t_bits tag, unsigned long mode_bits,
  548. const char *encoding,
  549. scm_t_string_failed_conversion_handler handler,
  550. scm_t_bits stream)
  551. {
  552. SCM ret;
  553. scm_t_port *entry;
  554. scm_t_port_internal *pti;
  555. scm_t_ptob_descriptor *ptob;
  556. entry = scm_gc_typed_calloc (scm_t_port);
  557. pti = scm_gc_typed_calloc (scm_t_port_internal);
  558. ptob = scm_c_port_type_ref (SCM_TC2PTOBNUM (tag));
  559. ret = scm_words (tag | mode_bits, 3);
  560. SCM_SET_CELL_WORD_1 (ret, (scm_t_bits) entry);
  561. SCM_SET_CELL_WORD_2 (ret, (scm_t_bits) ptob);
  562. entry->lock = scm_gc_malloc_pointerless (sizeof (*entry->lock), "port lock");
  563. scm_i_pthread_mutex_init (entry->lock, scm_i_pthread_mutexattr_recursive);
  564. entry->internal = pti;
  565. entry->file_name = SCM_BOOL_F;
  566. entry->rw_active = SCM_PORT_NEITHER;
  567. entry->port = ret;
  568. entry->stream = stream;
  569. if (encoding_matches (encoding, "UTF-8"))
  570. {
  571. pti->encoding_mode = SCM_PORT_ENCODING_MODE_UTF8;
  572. entry->encoding = "UTF-8";
  573. }
  574. else if (encoding_matches (encoding, "ISO-8859-1"))
  575. {
  576. pti->encoding_mode = SCM_PORT_ENCODING_MODE_LATIN1;
  577. entry->encoding = "ISO-8859-1";
  578. }
  579. else
  580. {
  581. pti->encoding_mode = SCM_PORT_ENCODING_MODE_ICONV;
  582. entry->encoding = canonicalize_encoding (encoding);
  583. }
  584. entry->ilseq_handler = handler;
  585. pti->iconv_descriptors = NULL;
  586. pti->at_stream_start_for_bom_read = 1;
  587. pti->at_stream_start_for_bom_write = 1;
  588. pti->pending_eof = 0;
  589. pti->alist = SCM_EOL;
  590. if (SCM_PORT_DESCRIPTOR (ret)->free)
  591. scm_i_set_finalizer (SCM2PTR (ret), finalize_port, NULL);
  592. if (SCM_PORT_DESCRIPTOR (ret)->flags & SCM_PORT_TYPE_HAS_FLUSH)
  593. scm_weak_set_add_x (scm_i_port_weak_set, ret);
  594. return ret;
  595. }
  596. SCM
  597. scm_c_make_port (scm_t_bits tag, unsigned long mode_bits, scm_t_bits stream)
  598. {
  599. return scm_c_make_port_with_encoding (tag, mode_bits,
  600. scm_i_default_port_encoding (),
  601. scm_i_default_port_conversion_handler (),
  602. stream);
  603. }
  604. SCM
  605. scm_new_port_table_entry (scm_t_bits tag)
  606. {
  607. return scm_c_make_port (tag, 0, 0);
  608. }
  609. /* Predicates. */
  610. SCM_DEFINE (scm_port_p, "port?", 1, 0, 0,
  611. (SCM x),
  612. "Return a boolean indicating whether @var{x} is a port.\n"
  613. "Equivalent to @code{(or (input-port? @var{x}) (output-port?\n"
  614. "@var{x}))}.")
  615. #define FUNC_NAME s_scm_port_p
  616. {
  617. return scm_from_bool (SCM_PORTP (x));
  618. }
  619. #undef FUNC_NAME
  620. SCM_DEFINE (scm_input_port_p, "input-port?", 1, 0, 0,
  621. (SCM x),
  622. "Return @code{#t} if @var{x} is an input port, otherwise return\n"
  623. "@code{#f}. Any object satisfying this predicate also satisfies\n"
  624. "@code{port?}.")
  625. #define FUNC_NAME s_scm_input_port_p
  626. {
  627. return scm_from_bool (SCM_INPUT_PORT_P (x));
  628. }
  629. #undef FUNC_NAME
  630. SCM_DEFINE (scm_output_port_p, "output-port?", 1, 0, 0,
  631. (SCM x),
  632. "Return @code{#t} if @var{x} is an output port, otherwise return\n"
  633. "@code{#f}. Any object satisfying this predicate also satisfies\n"
  634. "@code{port?}.")
  635. #define FUNC_NAME s_scm_output_port_p
  636. {
  637. x = SCM_COERCE_OUTPORT (x);
  638. return scm_from_bool (SCM_OUTPUT_PORT_P (x));
  639. }
  640. #undef FUNC_NAME
  641. SCM_DEFINE (scm_port_closed_p, "port-closed?", 1, 0, 0,
  642. (SCM port),
  643. "Return @code{#t} if @var{port} is closed or @code{#f} if it is\n"
  644. "open.")
  645. #define FUNC_NAME s_scm_port_closed_p
  646. {
  647. SCM_VALIDATE_PORT (1, port);
  648. return scm_from_bool (!SCM_OPPORTP (port));
  649. }
  650. #undef FUNC_NAME
  651. SCM_DEFINE (scm_eof_object_p, "eof-object?", 1, 0, 0,
  652. (SCM x),
  653. "Return @code{#t} if @var{x} is an end-of-file object; otherwise\n"
  654. "return @code{#f}.")
  655. #define FUNC_NAME s_scm_eof_object_p
  656. {
  657. return scm_from_bool (SCM_EOF_OBJECT_P (x));
  658. }
  659. #undef FUNC_NAME
  660. /* Closing ports. */
  661. static void close_iconv_descriptors (scm_t_iconv_descriptors *id);
  662. /* scm_close_port
  663. * Call the close operation on a port object.
  664. * see also scm_close.
  665. */
  666. SCM_DEFINE (scm_close_port, "close-port", 1, 0, 0,
  667. (SCM port),
  668. "Close the specified port object. Return @code{#t} if it\n"
  669. "successfully closes a port or @code{#f} if it was already\n"
  670. "closed. An exception may be raised if an error occurs, for\n"
  671. "example when flushing buffered output. See also @ref{Ports and\n"
  672. "File Descriptors, close}, for a procedure which can close file\n"
  673. "descriptors.")
  674. #define FUNC_NAME s_scm_close_port
  675. {
  676. scm_t_port_internal *pti;
  677. int rv;
  678. port = SCM_COERCE_OUTPORT (port);
  679. SCM_VALIDATE_PORT (1, port);
  680. if (SCM_CLOSEDP (port))
  681. return SCM_BOOL_F;
  682. pti = SCM_PORT_GET_INTERNAL (port);
  683. SCM_CLR_PORT_OPEN_FLAG (port);
  684. if (SCM_PORT_DESCRIPTOR (port)->flags & SCM_PORT_TYPE_HAS_FLUSH)
  685. scm_weak_set_remove_x (scm_i_port_weak_set, port);
  686. if (SCM_PORT_DESCRIPTOR (port)->close)
  687. /* Note! This may throw an exception. Anything after this point
  688. should be resilient to non-local exits. */
  689. rv = SCM_PORT_DESCRIPTOR (port)->close (port);
  690. else
  691. rv = 0;
  692. if (pti->iconv_descriptors)
  693. {
  694. /* If we don't get here, the iconv_descriptors finalizer will
  695. clean up. */
  696. close_iconv_descriptors (pti->iconv_descriptors);
  697. pti->iconv_descriptors = NULL;
  698. }
  699. return scm_from_bool (rv >= 0);
  700. }
  701. #undef FUNC_NAME
  702. SCM_DEFINE (scm_close_input_port, "close-input-port", 1, 0, 0,
  703. (SCM port),
  704. "Close the specified input port object. The routine has no effect if\n"
  705. "the file has already been closed. An exception may be raised if an\n"
  706. "error occurs. The value returned is unspecified.\n\n"
  707. "See also @ref{Ports and File Descriptors, close}, for a procedure\n"
  708. "which can close file descriptors.")
  709. #define FUNC_NAME s_scm_close_input_port
  710. {
  711. SCM_VALIDATE_INPUT_PORT (1, port);
  712. scm_close_port (port);
  713. return SCM_UNSPECIFIED;
  714. }
  715. #undef FUNC_NAME
  716. SCM_DEFINE (scm_close_output_port, "close-output-port", 1, 0, 0,
  717. (SCM port),
  718. "Close the specified output port object. The routine has no effect if\n"
  719. "the file has already been closed. An exception may be raised if an\n"
  720. "error occurs. The value returned is unspecified.\n\n"
  721. "See also @ref{Ports and File Descriptors, close}, for a procedure\n"
  722. "which can close file descriptors.")
  723. #define FUNC_NAME s_scm_close_output_port
  724. {
  725. port = SCM_COERCE_OUTPORT (port);
  726. SCM_VALIDATE_OUTPUT_PORT (1, port);
  727. scm_close_port (port);
  728. return SCM_UNSPECIFIED;
  729. }
  730. #undef FUNC_NAME
  731. /* Encoding characters to byte streams, and decoding byte streams to
  732. characters. */
  733. /* A fluid specifying the default encoding for newly created ports. If it is
  734. a string, that is the encoding. If it is #f, it is in the "native"
  735. (Latin-1) encoding. */
  736. SCM_VARIABLE (default_port_encoding_var, "%default-port-encoding");
  737. static int scm_port_encoding_init = 0;
  738. /* Use ENCODING as the default encoding for future ports. */
  739. void
  740. scm_i_set_default_port_encoding (const char *encoding)
  741. {
  742. if (!scm_port_encoding_init
  743. || !scm_is_fluid (SCM_VARIABLE_REF (default_port_encoding_var)))
  744. scm_misc_error (NULL, "tried to set port encoding fluid before it is initialized",
  745. SCM_EOL);
  746. if (encoding_matches (encoding, "ISO-8859-1"))
  747. scm_fluid_set_x (SCM_VARIABLE_REF (default_port_encoding_var), SCM_BOOL_F);
  748. else
  749. scm_fluid_set_x (SCM_VARIABLE_REF (default_port_encoding_var),
  750. scm_from_latin1_string (canonicalize_encoding (encoding)));
  751. }
  752. /* Return the name of the default encoding for newly created ports. */
  753. const char *
  754. scm_i_default_port_encoding (void)
  755. {
  756. if (!scm_port_encoding_init)
  757. return "ISO-8859-1";
  758. else if (!scm_is_fluid (SCM_VARIABLE_REF (default_port_encoding_var)))
  759. return "ISO-8859-1";
  760. else
  761. {
  762. SCM encoding;
  763. encoding = scm_fluid_ref (SCM_VARIABLE_REF (default_port_encoding_var));
  764. if (!scm_is_string (encoding))
  765. return "ISO-8859-1";
  766. else
  767. return scm_i_string_chars (encoding);
  768. }
  769. }
  770. /* A fluid specifying the default conversion handler for newly created
  771. ports. Its value should be one of the symbols below. */
  772. SCM_VARIABLE (default_conversion_strategy_var,
  773. "%default-port-conversion-strategy");
  774. /* Whether the above fluid is initialized. */
  775. static int scm_conversion_strategy_init = 0;
  776. /* The possible conversion strategies. */
  777. SCM_SYMBOL (sym_error, "error");
  778. SCM_SYMBOL (sym_substitute, "substitute");
  779. SCM_SYMBOL (sym_escape, "escape");
  780. /* Return the default failed encoding conversion policy for new created
  781. ports. */
  782. scm_t_string_failed_conversion_handler
  783. scm_i_default_port_conversion_handler (void)
  784. {
  785. scm_t_string_failed_conversion_handler handler;
  786. if (!scm_conversion_strategy_init
  787. || !scm_is_fluid (SCM_VARIABLE_REF (default_conversion_strategy_var)))
  788. handler = SCM_FAILED_CONVERSION_QUESTION_MARK;
  789. else
  790. {
  791. SCM fluid, value;
  792. fluid = SCM_VARIABLE_REF (default_conversion_strategy_var);
  793. value = scm_fluid_ref (fluid);
  794. if (scm_is_eq (sym_substitute, value))
  795. handler = SCM_FAILED_CONVERSION_QUESTION_MARK;
  796. else if (scm_is_eq (sym_escape, value))
  797. handler = SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE;
  798. else
  799. /* Default to 'error also when the fluid's value is not one of
  800. the valid symbols. */
  801. handler = SCM_FAILED_CONVERSION_ERROR;
  802. }
  803. return handler;
  804. }
  805. /* Use HANDLER as the default conversion strategy for future ports. */
  806. void
  807. scm_i_set_default_port_conversion_handler (scm_t_string_failed_conversion_handler
  808. handler)
  809. {
  810. SCM strategy;
  811. if (!scm_conversion_strategy_init
  812. || !scm_is_fluid (SCM_VARIABLE_REF (default_conversion_strategy_var)))
  813. scm_misc_error (NULL, "tried to set conversion strategy fluid before it is initialized",
  814. SCM_EOL);
  815. switch (handler)
  816. {
  817. case SCM_FAILED_CONVERSION_ERROR:
  818. strategy = sym_error;
  819. break;
  820. case SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE:
  821. strategy = sym_escape;
  822. break;
  823. case SCM_FAILED_CONVERSION_QUESTION_MARK:
  824. strategy = sym_substitute;
  825. break;
  826. default:
  827. abort ();
  828. }
  829. scm_fluid_set_x (SCM_VARIABLE_REF (default_conversion_strategy_var),
  830. strategy);
  831. }
  832. static void
  833. scm_i_unget_bytes_unlocked (const unsigned char *buf, size_t len, SCM port);
  834. /* If the next LEN bytes from PORT are equal to those in BYTES, then
  835. return 1, else return 0. Leave the port position unchanged. */
  836. static int
  837. looking_at_bytes (SCM port, const unsigned char *bytes, int len)
  838. {
  839. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  840. int i = 0;
  841. while (i < len && scm_peek_byte_or_eof_unlocked (port) == bytes[i])
  842. {
  843. pt->read_pos++;
  844. i++;
  845. }
  846. scm_i_unget_bytes_unlocked (bytes, i, port);
  847. return (i == len);
  848. }
  849. static const unsigned char scm_utf8_bom[3] = {0xEF, 0xBB, 0xBF};
  850. static const unsigned char scm_utf16be_bom[2] = {0xFE, 0xFF};
  851. static const unsigned char scm_utf16le_bom[2] = {0xFF, 0xFE};
  852. static const unsigned char scm_utf32be_bom[4] = {0x00, 0x00, 0xFE, 0xFF};
  853. static const unsigned char scm_utf32le_bom[4] = {0xFF, 0xFE, 0x00, 0x00};
  854. /* Decide what byte order to use for a UTF-16 port. Return "UTF-16BE"
  855. or "UTF-16LE". MODE must be either SCM_PORT_READ or SCM_PORT_WRITE,
  856. and specifies which operation is about to be done. The MODE
  857. determines how we will decide the byte order. We deliberately avoid
  858. reading from the port unless the user is about to do so. If the user
  859. is about to read, then we look for a BOM, and if present, we use it
  860. to determine the byte order. Otherwise we choose big endian, as
  861. recommended by the Unicode Standard. Note that the BOM (if any) is
  862. not consumed here. */
  863. static const char *
  864. decide_utf16_encoding (SCM port, scm_t_port_rw_active mode)
  865. {
  866. if (mode == SCM_PORT_READ
  867. && SCM_PORT_GET_INTERNAL (port)->at_stream_start_for_bom_read
  868. && looking_at_bytes (port, scm_utf16le_bom, sizeof scm_utf16le_bom))
  869. return "UTF-16LE";
  870. else
  871. return "UTF-16BE";
  872. }
  873. /* Decide what byte order to use for a UTF-32 port. Return "UTF-32BE"
  874. or "UTF-32LE". See the comment above 'decide_utf16_encoding' for
  875. details. */
  876. static const char *
  877. decide_utf32_encoding (SCM port, scm_t_port_rw_active mode)
  878. {
  879. if (mode == SCM_PORT_READ
  880. && SCM_PORT_GET_INTERNAL (port)->at_stream_start_for_bom_read
  881. && looking_at_bytes (port, scm_utf32le_bom, sizeof scm_utf32le_bom))
  882. return "UTF-32LE";
  883. else
  884. return "UTF-32BE";
  885. }
  886. static void
  887. finalize_iconv_descriptors (void *ptr, void *data)
  888. {
  889. close_iconv_descriptors (ptr);
  890. }
  891. static scm_t_iconv_descriptors *
  892. open_iconv_descriptors (const char *encoding, int reading, int writing)
  893. {
  894. scm_t_iconv_descriptors *id;
  895. iconv_t input_cd, output_cd;
  896. size_t i;
  897. input_cd = (iconv_t) -1;
  898. output_cd = (iconv_t) -1;
  899. for (i = 0; encoding[i]; i++)
  900. if (encoding[i] > 127)
  901. goto invalid_encoding;
  902. if (reading)
  903. {
  904. /* Open an input iconv conversion descriptor, from ENCODING
  905. to UTF-8. We choose UTF-8, not UTF-32, because iconv
  906. implementations can typically convert from anything to
  907. UTF-8, but not to UTF-32 (see
  908. <http://lists.gnu.org/archive/html/bug-libunistring/2010-09/msg00007.html>). */
  909. /* Assume opening an iconv descriptor causes about 16 KB of
  910. allocation. */
  911. scm_gc_register_allocation (16 * 1024);
  912. input_cd = iconv_open ("UTF-8", encoding);
  913. if (input_cd == (iconv_t) -1)
  914. goto invalid_encoding;
  915. }
  916. if (writing)
  917. {
  918. /* Assume opening an iconv descriptor causes about 16 KB of
  919. allocation. */
  920. scm_gc_register_allocation (16 * 1024);
  921. output_cd = iconv_open (encoding, "UTF-8");
  922. if (output_cd == (iconv_t) -1)
  923. {
  924. if (input_cd != (iconv_t) -1)
  925. iconv_close (input_cd);
  926. goto invalid_encoding;
  927. }
  928. }
  929. id = scm_gc_malloc_pointerless (sizeof (*id), "iconv descriptors");
  930. id->input_cd = input_cd;
  931. id->output_cd = output_cd;
  932. /* Register a finalizer to close the descriptors. */
  933. scm_i_set_finalizer (id, finalize_iconv_descriptors, NULL);
  934. return id;
  935. invalid_encoding:
  936. {
  937. SCM err;
  938. err = scm_from_latin1_string (encoding);
  939. scm_misc_error ("open_iconv_descriptors",
  940. "invalid or unknown character encoding ~s",
  941. scm_list_1 (err));
  942. }
  943. }
  944. static void
  945. close_iconv_descriptors (scm_t_iconv_descriptors *id)
  946. {
  947. if (id->input_cd != (iconv_t) -1)
  948. iconv_close (id->input_cd);
  949. if (id->output_cd != (iconv_t) -1)
  950. iconv_close (id->output_cd);
  951. id->input_cd = (void *) -1;
  952. id->output_cd = (void *) -1;
  953. }
  954. scm_t_iconv_descriptors *
  955. scm_i_port_iconv_descriptors (SCM port, scm_t_port_rw_active mode)
  956. {
  957. scm_t_port_internal *pti = SCM_PORT_GET_INTERNAL (port);
  958. assert (pti->encoding_mode == SCM_PORT_ENCODING_MODE_ICONV);
  959. if (!pti->iconv_descriptors)
  960. {
  961. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  962. const char *precise_encoding;
  963. if (!pt->encoding)
  964. pt->encoding = "ISO-8859-1";
  965. /* If the specified encoding is UTF-16 or UTF-32, then make
  966. that more precise by deciding what byte order to use. */
  967. if (strcmp (pt->encoding, "UTF-16") == 0)
  968. precise_encoding = decide_utf16_encoding (port, mode);
  969. else if (strcmp (pt->encoding, "UTF-32") == 0)
  970. precise_encoding = decide_utf32_encoding (port, mode);
  971. else
  972. precise_encoding = pt->encoding;
  973. pti->iconv_descriptors =
  974. open_iconv_descriptors (precise_encoding,
  975. SCM_INPUT_PORT_P (port),
  976. SCM_OUTPUT_PORT_P (port));
  977. }
  978. return pti->iconv_descriptors;
  979. }
  980. /* The name of the encoding is itself encoded in ASCII. */
  981. void
  982. scm_i_set_port_encoding_x (SCM port, const char *encoding)
  983. {
  984. scm_t_port *pt;
  985. scm_t_port_internal *pti;
  986. scm_t_iconv_descriptors *prev;
  987. /* Set the character encoding for this port. */
  988. pt = SCM_PTAB_ENTRY (port);
  989. pti = SCM_PORT_GET_INTERNAL (port);
  990. prev = pti->iconv_descriptors;
  991. /* In order to handle cases where the encoding changes mid-stream
  992. (e.g. within an HTTP stream, or within a file that is composed of
  993. segments with different encodings), we consider this to be "stream
  994. start" for purposes of BOM handling, regardless of our actual file
  995. position. */
  996. pti->at_stream_start_for_bom_read = 1;
  997. pti->at_stream_start_for_bom_write = 1;
  998. if (encoding_matches (encoding, "UTF-8"))
  999. {
  1000. pt->encoding = "UTF-8";
  1001. pti->encoding_mode = SCM_PORT_ENCODING_MODE_UTF8;
  1002. }
  1003. else if (encoding_matches (encoding, "ISO-8859-1"))
  1004. {
  1005. pt->encoding = "ISO-8859-1";
  1006. pti->encoding_mode = SCM_PORT_ENCODING_MODE_LATIN1;
  1007. }
  1008. else
  1009. {
  1010. pt->encoding = canonicalize_encoding (encoding);
  1011. pti->encoding_mode = SCM_PORT_ENCODING_MODE_ICONV;
  1012. }
  1013. pti->iconv_descriptors = NULL;
  1014. if (prev)
  1015. close_iconv_descriptors (prev);
  1016. }
  1017. SCM_DEFINE (scm_port_encoding, "port-encoding", 1, 0, 0,
  1018. (SCM port),
  1019. "Returns, as a string, the character encoding that @var{port}\n"
  1020. "uses to interpret its input and output.\n")
  1021. #define FUNC_NAME s_scm_port_encoding
  1022. {
  1023. SCM_VALIDATE_PORT (1, port);
  1024. return scm_from_latin1_string (SCM_PTAB_ENTRY (port)->encoding);
  1025. }
  1026. #undef FUNC_NAME
  1027. SCM_DEFINE (scm_set_port_encoding_x, "set-port-encoding!", 2, 0, 0,
  1028. (SCM port, SCM enc),
  1029. "Sets the character encoding that will be used to interpret all\n"
  1030. "port I/O. New ports are created with the encoding\n"
  1031. "appropriate for the current locale if @code{setlocale} has \n"
  1032. "been called or ISO-8859-1 otherwise\n"
  1033. "and this procedure can be used to modify that encoding.\n")
  1034. #define FUNC_NAME s_scm_set_port_encoding_x
  1035. {
  1036. char *enc_str;
  1037. SCM_VALIDATE_PORT (1, port);
  1038. SCM_VALIDATE_STRING (2, enc);
  1039. enc_str = scm_to_latin1_string (enc);
  1040. scm_i_set_port_encoding_x (port, enc_str);
  1041. free (enc_str);
  1042. return SCM_UNSPECIFIED;
  1043. }
  1044. #undef FUNC_NAME
  1045. SCM_DEFINE (scm_port_conversion_strategy, "port-conversion-strategy",
  1046. 1, 0, 0, (SCM port),
  1047. "Returns the behavior of the port when handling a character that\n"
  1048. "is not representable in the port's current encoding.\n"
  1049. "It returns the symbol @code{error} if unrepresentable characters\n"
  1050. "should cause exceptions, @code{substitute} if the port should\n"
  1051. "try to replace unrepresentable characters with question marks or\n"
  1052. "approximate characters, or @code{escape} if unrepresentable\n"
  1053. "characters should be converted to string escapes.\n"
  1054. "\n"
  1055. "If @var{port} is @code{#f}, then the current default behavior\n"
  1056. "will be returned. New ports will have this default behavior\n"
  1057. "when they are created.\n")
  1058. #define FUNC_NAME s_scm_port_conversion_strategy
  1059. {
  1060. scm_t_string_failed_conversion_handler h;
  1061. if (scm_is_false (port))
  1062. h = scm_i_default_port_conversion_handler ();
  1063. else
  1064. {
  1065. scm_t_port *pt;
  1066. SCM_VALIDATE_OPPORT (1, port);
  1067. pt = SCM_PTAB_ENTRY (port);
  1068. h = pt->ilseq_handler;
  1069. }
  1070. if (h == SCM_FAILED_CONVERSION_ERROR)
  1071. return scm_from_latin1_symbol ("error");
  1072. else if (h == SCM_FAILED_CONVERSION_QUESTION_MARK)
  1073. return scm_from_latin1_symbol ("substitute");
  1074. else if (h == SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE)
  1075. return scm_from_latin1_symbol ("escape");
  1076. else
  1077. abort ();
  1078. /* Never gets here. */
  1079. return SCM_UNDEFINED;
  1080. }
  1081. #undef FUNC_NAME
  1082. SCM_DEFINE (scm_set_port_conversion_strategy_x, "set-port-conversion-strategy!",
  1083. 2, 0, 0,
  1084. (SCM port, SCM sym),
  1085. "Sets the behavior of the interpreter when outputting a character\n"
  1086. "that is not representable in the port's current encoding.\n"
  1087. "@var{sym} can be either @code{'error}, @code{'substitute}, or\n"
  1088. "@code{'escape}. If it is @code{'error}, an error will be thrown\n"
  1089. "when an unconvertible character is encountered. If it is\n"
  1090. "@code{'substitute}, then unconvertible characters will \n"
  1091. "be replaced with approximate characters, or with question marks\n"
  1092. "if no approximately correct character is available.\n"
  1093. "If it is @code{'escape},\n"
  1094. "it will appear as a hex escape when output.\n"
  1095. "\n"
  1096. "If @var{port} is an open port, the conversion error behavior\n"
  1097. "is set for that port. If it is @code{#f}, it is set as the\n"
  1098. "default behavior for any future ports that get created in\n"
  1099. "this thread.\n")
  1100. #define FUNC_NAME s_scm_set_port_conversion_strategy_x
  1101. {
  1102. scm_t_string_failed_conversion_handler handler;
  1103. if (scm_is_eq (sym, sym_error))
  1104. handler = SCM_FAILED_CONVERSION_ERROR;
  1105. else if (scm_is_eq (sym, sym_substitute))
  1106. handler = SCM_FAILED_CONVERSION_QUESTION_MARK;
  1107. else if (scm_is_eq (sym, sym_escape))
  1108. handler = SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE;
  1109. else
  1110. SCM_MISC_ERROR ("unknown conversion strategy ~s", scm_list_1 (sym));
  1111. if (scm_is_false (port))
  1112. scm_i_set_default_port_conversion_handler (handler);
  1113. else
  1114. {
  1115. SCM_VALIDATE_OPPORT (1, port);
  1116. SCM_PTAB_ENTRY (port)->ilseq_handler = handler;
  1117. }
  1118. return SCM_UNSPECIFIED;
  1119. }
  1120. #undef FUNC_NAME
  1121. /* The port lock. */
  1122. static void
  1123. lock_port (void *mutex)
  1124. {
  1125. scm_i_pthread_mutex_lock ((scm_i_pthread_mutex_t *) mutex);
  1126. }
  1127. static void
  1128. unlock_port (void *mutex)
  1129. {
  1130. scm_i_pthread_mutex_unlock ((scm_i_pthread_mutex_t *) mutex);
  1131. }
  1132. void
  1133. scm_dynwind_lock_port (SCM port)
  1134. #define FUNC_NAME "dynwind-lock-port"
  1135. {
  1136. scm_i_pthread_mutex_t *lock;
  1137. SCM_VALIDATE_OPPORT (SCM_ARG1, port);
  1138. scm_c_lock_port (port, &lock);
  1139. if (lock)
  1140. {
  1141. scm_dynwind_unwind_handler (unlock_port, lock, SCM_F_WIND_EXPLICITLY);
  1142. scm_dynwind_rewind_handler (lock_port, lock, 0);
  1143. }
  1144. }
  1145. #undef FUNC_NAME
  1146. /* Input. */
  1147. int
  1148. scm_get_byte_or_eof (SCM port)
  1149. {
  1150. scm_i_pthread_mutex_t *lock;
  1151. int ret;
  1152. scm_c_lock_port (port, &lock);
  1153. ret = scm_get_byte_or_eof_unlocked (port);
  1154. if (lock)
  1155. scm_i_pthread_mutex_unlock (lock);
  1156. return ret;
  1157. }
  1158. int
  1159. scm_peek_byte_or_eof (SCM port)
  1160. {
  1161. scm_i_pthread_mutex_t *lock;
  1162. int ret;
  1163. scm_c_lock_port (port, &lock);
  1164. ret = scm_peek_byte_or_eof_unlocked (port);
  1165. if (lock)
  1166. scm_i_pthread_mutex_unlock (lock);
  1167. return ret;
  1168. }
  1169. /* scm_c_read
  1170. *
  1171. * Used by an application to read arbitrary number of bytes from an
  1172. * SCM port. Same semantics as libc read, except that scm_c_read only
  1173. * returns less than SIZE bytes if at end-of-file.
  1174. *
  1175. * Warning: Doesn't update port line and column counts! */
  1176. /* This structure, and the following swap_buffer function, are used
  1177. for temporarily swapping a port's own read buffer, and the buffer
  1178. that the caller of scm_c_read provides. */
  1179. struct port_and_swap_buffer
  1180. {
  1181. scm_t_port *pt;
  1182. unsigned char *buffer;
  1183. size_t size;
  1184. };
  1185. static void
  1186. swap_buffer (void *data)
  1187. {
  1188. struct port_and_swap_buffer *psb = (struct port_and_swap_buffer *) data;
  1189. unsigned char *old_buf = psb->pt->read_buf;
  1190. size_t old_size = psb->pt->read_buf_size;
  1191. /* Make the port use (buffer, size) from the struct. */
  1192. psb->pt->read_pos = psb->pt->read_buf = psb->pt->read_end = psb->buffer;
  1193. psb->pt->read_buf_size = psb->size;
  1194. /* Save the port's old (buffer, size) in the struct. */
  1195. psb->buffer = old_buf;
  1196. psb->size = old_size;
  1197. }
  1198. static int scm_i_fill_input_unlocked (SCM port);
  1199. size_t
  1200. scm_c_read_unlocked (SCM port, void *buffer, size_t size)
  1201. #define FUNC_NAME "scm_c_read"
  1202. {
  1203. scm_t_port *pt;
  1204. scm_t_port_internal *pti;
  1205. size_t n_read = 0, n_available;
  1206. struct port_and_swap_buffer psb;
  1207. SCM_VALIDATE_OPINPORT (1, port);
  1208. pt = SCM_PTAB_ENTRY (port);
  1209. pti = SCM_PORT_GET_INTERNAL (port);
  1210. if (pt->rw_active == SCM_PORT_WRITE)
  1211. SCM_PORT_DESCRIPTOR (port)->flush (port);
  1212. if (pt->rw_random)
  1213. pt->rw_active = SCM_PORT_READ;
  1214. /* Take bytes first from the port's read buffer. */
  1215. if (pt->read_pos < pt->read_end)
  1216. {
  1217. n_available = min (size, pt->read_end - pt->read_pos);
  1218. memcpy (buffer, pt->read_pos, n_available);
  1219. buffer = (char *) buffer + n_available;
  1220. pt->read_pos += n_available;
  1221. n_read += n_available;
  1222. size -= n_available;
  1223. }
  1224. /* Avoid the scm_dynwind_* costs if we now have enough data. */
  1225. if (size == 0)
  1226. return n_read;
  1227. /* Now we will call scm_i_fill_input_unlocked repeatedly until we have
  1228. read the requested number of bytes. (Note that a single
  1229. scm_i_fill_input_unlocked call does not guarantee to fill the whole
  1230. of the port's read buffer.) */
  1231. if (pt->read_buf_size <= 1
  1232. && pti->encoding_mode == SCM_PORT_ENCODING_MODE_LATIN1)
  1233. {
  1234. /* The port that we are reading from is unbuffered - i.e. does not
  1235. have its own persistent buffer - but we have a buffer, provided
  1236. by our caller, that is the right size for the data that is
  1237. wanted. For the following scm_i_fill_input_unlocked calls,
  1238. therefore, we use the buffer in hand as the port's read buffer.
  1239. We need to make sure that the port's normal (1 byte) buffer is
  1240. reinstated in case one of the scm_i_fill_input_unlocked ()
  1241. calls throws an exception; we use the scm_dynwind_* API to
  1242. achieve that.
  1243. A consequence of this optimization is that the fill_input
  1244. functions can't unget characters. That'll push data to the
  1245. pushback buffer instead of this psb buffer. */
  1246. #if SCM_DEBUG == 1
  1247. unsigned char *pback = pt->putback_buf;
  1248. #endif
  1249. psb.pt = pt;
  1250. psb.buffer = buffer;
  1251. psb.size = size;
  1252. scm_dynwind_begin (SCM_F_DYNWIND_REWINDABLE);
  1253. scm_dynwind_rewind_handler (swap_buffer, &psb, SCM_F_WIND_EXPLICITLY);
  1254. scm_dynwind_unwind_handler (swap_buffer, &psb, SCM_F_WIND_EXPLICITLY);
  1255. /* Call scm_i_fill_input_unlocked until we have all the bytes that
  1256. we need, or we hit EOF. */
  1257. while (pt->read_buf_size && (scm_i_fill_input_unlocked (port) != EOF))
  1258. {
  1259. pt->read_buf_size -= (pt->read_end - pt->read_pos);
  1260. pt->read_pos = pt->read_buf = pt->read_end;
  1261. }
  1262. #if SCM_DEBUG == 1
  1263. if (pback != pt->putback_buf
  1264. || pt->read_buf - (unsigned char *) buffer < 0)
  1265. scm_misc_error (FUNC_NAME,
  1266. "scm_c_read must not call a fill function that pushes "
  1267. "back characters onto an unbuffered port", SCM_EOL);
  1268. #endif
  1269. n_read += pt->read_buf - (unsigned char *) buffer;
  1270. /* Reinstate the port's normal buffer. */
  1271. scm_dynwind_end ();
  1272. }
  1273. else
  1274. {
  1275. /* The port has its own buffer. It is important that we use it,
  1276. even if it happens to be smaller than our caller's buffer, so
  1277. that a custom port implementation's entry points (in
  1278. particular, fill_input) can rely on the buffer always being
  1279. the same as they first set up. */
  1280. while (size && (scm_i_fill_input_unlocked (port) != EOF))
  1281. {
  1282. n_available = min (size, pt->read_end - pt->read_pos);
  1283. memcpy (buffer, pt->read_pos, n_available);
  1284. buffer = (char *) buffer + n_available;
  1285. pt->read_pos += n_available;
  1286. n_read += n_available;
  1287. size -= n_available;
  1288. }
  1289. }
  1290. return n_read;
  1291. }
  1292. #undef FUNC_NAME
  1293. size_t
  1294. scm_c_read (SCM port, void *buffer, size_t size)
  1295. {
  1296. scm_i_pthread_mutex_t *lock;
  1297. size_t ret;
  1298. scm_c_lock_port (port, &lock);
  1299. ret = scm_c_read_unlocked (port, buffer, size);
  1300. if (lock)
  1301. scm_i_pthread_mutex_unlock (lock);
  1302. return ret;
  1303. }
  1304. /* Update the line and column number of PORT after consumption of C. */
  1305. static inline void
  1306. update_port_lf (scm_t_wchar c, SCM port)
  1307. {
  1308. switch (c)
  1309. {
  1310. case '\a':
  1311. case EOF:
  1312. break;
  1313. case '\b':
  1314. SCM_DECCOL (port);
  1315. break;
  1316. case '\n':
  1317. SCM_INCLINE (port);
  1318. break;
  1319. case '\r':
  1320. SCM_ZEROCOL (port);
  1321. break;
  1322. case '\t':
  1323. SCM_TABCOL (port);
  1324. break;
  1325. default:
  1326. SCM_INCCOL (port);
  1327. break;
  1328. }
  1329. }
  1330. #define SCM_MBCHAR_BUF_SIZE (4)
  1331. /* Convert the SIZE-byte UTF-8 sequence in UTF8_BUF to a codepoint.
  1332. UTF8_BUF is assumed to contain a valid UTF-8 sequence. */
  1333. static scm_t_wchar
  1334. utf8_to_codepoint (const scm_t_uint8 *utf8_buf, size_t size)
  1335. {
  1336. scm_t_wchar codepoint;
  1337. if (utf8_buf[0] <= 0x7f)
  1338. {
  1339. assert (size == 1);
  1340. codepoint = utf8_buf[0];
  1341. }
  1342. else if ((utf8_buf[0] & 0xe0) == 0xc0)
  1343. {
  1344. assert (size == 2);
  1345. codepoint = ((scm_t_wchar) utf8_buf[0] & 0x1f) << 6UL
  1346. | (utf8_buf[1] & 0x3f);
  1347. }
  1348. else if ((utf8_buf[0] & 0xf0) == 0xe0)
  1349. {
  1350. assert (size == 3);
  1351. codepoint = ((scm_t_wchar) utf8_buf[0] & 0x0f) << 12UL
  1352. | ((scm_t_wchar) utf8_buf[1] & 0x3f) << 6UL
  1353. | (utf8_buf[2] & 0x3f);
  1354. }
  1355. else
  1356. {
  1357. assert (size == 4);
  1358. codepoint = ((scm_t_wchar) utf8_buf[0] & 0x07) << 18UL
  1359. | ((scm_t_wchar) utf8_buf[1] & 0x3f) << 12UL
  1360. | ((scm_t_wchar) utf8_buf[2] & 0x3f) << 6UL
  1361. | (utf8_buf[3] & 0x3f);
  1362. }
  1363. return codepoint;
  1364. }
  1365. /* Read a UTF-8 sequence from PORT. On success, return 0 and set
  1366. *CODEPOINT to the codepoint that was read, fill BUF with its UTF-8
  1367. representation, and set *LEN to the length in bytes. Return
  1368. `EILSEQ' on error. */
  1369. static int
  1370. get_utf8_codepoint (SCM port, scm_t_wchar *codepoint,
  1371. scm_t_uint8 buf[SCM_MBCHAR_BUF_SIZE], size_t *len)
  1372. {
  1373. #define ASSERT_NOT_EOF(b) \
  1374. if (SCM_UNLIKELY ((b) == EOF)) \
  1375. goto invalid_seq
  1376. #define CONSUME_PEEKED_BYTE() \
  1377. pt->read_pos++
  1378. int byte;
  1379. scm_t_port *pt;
  1380. *len = 0;
  1381. pt = SCM_PTAB_ENTRY (port);
  1382. byte = scm_get_byte_or_eof_unlocked (port);
  1383. if (byte == EOF)
  1384. {
  1385. *codepoint = EOF;
  1386. return 0;
  1387. }
  1388. buf[0] = (scm_t_uint8) byte;
  1389. *len = 1;
  1390. if (buf[0] <= 0x7f)
  1391. /* 1-byte form. */
  1392. *codepoint = buf[0];
  1393. else if (buf[0] >= 0xc2 && buf[0] <= 0xdf)
  1394. {
  1395. /* 2-byte form. */
  1396. byte = scm_peek_byte_or_eof_unlocked (port);
  1397. ASSERT_NOT_EOF (byte);
  1398. if (SCM_UNLIKELY ((byte & 0xc0) != 0x80))
  1399. goto invalid_seq;
  1400. CONSUME_PEEKED_BYTE ();
  1401. buf[1] = (scm_t_uint8) byte;
  1402. *len = 2;
  1403. *codepoint = ((scm_t_wchar) buf[0] & 0x1f) << 6UL
  1404. | (buf[1] & 0x3f);
  1405. }
  1406. else if ((buf[0] & 0xf0) == 0xe0)
  1407. {
  1408. /* 3-byte form. */
  1409. byte = scm_peek_byte_or_eof_unlocked (port);
  1410. ASSERT_NOT_EOF (byte);
  1411. if (SCM_UNLIKELY ((byte & 0xc0) != 0x80
  1412. || (buf[0] == 0xe0 && byte < 0xa0)
  1413. || (buf[0] == 0xed && byte > 0x9f)))
  1414. goto invalid_seq;
  1415. CONSUME_PEEKED_BYTE ();
  1416. buf[1] = (scm_t_uint8) byte;
  1417. *len = 2;
  1418. byte = scm_peek_byte_or_eof_unlocked (port);
  1419. ASSERT_NOT_EOF (byte);
  1420. if (SCM_UNLIKELY ((byte & 0xc0) != 0x80))
  1421. goto invalid_seq;
  1422. CONSUME_PEEKED_BYTE ();
  1423. buf[2] = (scm_t_uint8) byte;
  1424. *len = 3;
  1425. *codepoint = ((scm_t_wchar) buf[0] & 0x0f) << 12UL
  1426. | ((scm_t_wchar) buf[1] & 0x3f) << 6UL
  1427. | (buf[2] & 0x3f);
  1428. }
  1429. else if (buf[0] >= 0xf0 && buf[0] <= 0xf4)
  1430. {
  1431. /* 4-byte form. */
  1432. byte = scm_peek_byte_or_eof_unlocked (port);
  1433. ASSERT_NOT_EOF (byte);
  1434. if (SCM_UNLIKELY (((byte & 0xc0) != 0x80)
  1435. || (buf[0] == 0xf0 && byte < 0x90)
  1436. || (buf[0] == 0xf4 && byte > 0x8f)))
  1437. goto invalid_seq;
  1438. CONSUME_PEEKED_BYTE ();
  1439. buf[1] = (scm_t_uint8) byte;
  1440. *len = 2;
  1441. byte = scm_peek_byte_or_eof_unlocked (port);
  1442. ASSERT_NOT_EOF (byte);
  1443. if (SCM_UNLIKELY ((byte & 0xc0) != 0x80))
  1444. goto invalid_seq;
  1445. CONSUME_PEEKED_BYTE ();
  1446. buf[2] = (scm_t_uint8) byte;
  1447. *len = 3;
  1448. byte = scm_peek_byte_or_eof_unlocked (port);
  1449. ASSERT_NOT_EOF (byte);
  1450. if (SCM_UNLIKELY ((byte & 0xc0) != 0x80))
  1451. goto invalid_seq;
  1452. CONSUME_PEEKED_BYTE ();
  1453. buf[3] = (scm_t_uint8) byte;
  1454. *len = 4;
  1455. *codepoint = ((scm_t_wchar) buf[0] & 0x07) << 18UL
  1456. | ((scm_t_wchar) buf[1] & 0x3f) << 12UL
  1457. | ((scm_t_wchar) buf[2] & 0x3f) << 6UL
  1458. | (buf[3] & 0x3f);
  1459. }
  1460. else
  1461. goto invalid_seq;
  1462. return 0;
  1463. invalid_seq:
  1464. /* Here we could choose the consume the faulty byte when it's not a
  1465. valid starting byte, but it's not a requirement. What Section 3.9
  1466. of Unicode 6.0.0 mandates, though, is to not consume a byte that
  1467. would otherwise be a valid starting byte. */
  1468. return EILSEQ;
  1469. #undef CONSUME_PEEKED_BYTE
  1470. #undef ASSERT_NOT_EOF
  1471. }
  1472. /* Read an ISO-8859-1 codepoint (a byte) from PORT. On success, return
  1473. 0 and set *CODEPOINT to the codepoint that was read, fill BUF with
  1474. its UTF-8 representation, and set *LEN to the length in bytes.
  1475. Return `EILSEQ' on error. */
  1476. static int
  1477. get_latin1_codepoint (SCM port, scm_t_wchar *codepoint,
  1478. char buf[SCM_MBCHAR_BUF_SIZE], size_t *len)
  1479. {
  1480. *codepoint = scm_get_byte_or_eof_unlocked (port);
  1481. if (*codepoint == EOF)
  1482. *len = 0;
  1483. else
  1484. {
  1485. *len = 1;
  1486. buf[0] = *codepoint;
  1487. }
  1488. return 0;
  1489. }
  1490. /* Likewise, read a byte sequence from PORT, passing it through its
  1491. input conversion descriptor. */
  1492. static int
  1493. get_iconv_codepoint (SCM port, scm_t_wchar *codepoint,
  1494. char buf[SCM_MBCHAR_BUF_SIZE], size_t *len)
  1495. {
  1496. scm_t_iconv_descriptors *id;
  1497. scm_t_uint8 utf8_buf[SCM_MBCHAR_BUF_SIZE];
  1498. size_t input_size = 0;
  1499. id = scm_i_port_iconv_descriptors (port, SCM_PORT_READ);
  1500. for (;;)
  1501. {
  1502. int byte_read;
  1503. char *input, *output;
  1504. size_t input_left, output_left, done;
  1505. byte_read = scm_get_byte_or_eof_unlocked (port);
  1506. if (SCM_UNLIKELY (byte_read == EOF))
  1507. {
  1508. if (SCM_LIKELY (input_size == 0))
  1509. {
  1510. *codepoint = (scm_t_wchar) EOF;
  1511. *len = input_size;
  1512. return 0;
  1513. }
  1514. else
  1515. {
  1516. /* EOF found in the middle of a multibyte character. */
  1517. scm_i_set_pending_eof (port);
  1518. return EILSEQ;
  1519. }
  1520. }
  1521. buf[input_size++] = byte_read;
  1522. input = buf;
  1523. input_left = input_size;
  1524. output = (char *) utf8_buf;
  1525. output_left = sizeof (utf8_buf);
  1526. done = iconv (id->input_cd, &input, &input_left, &output, &output_left);
  1527. if (done == (size_t) -1)
  1528. {
  1529. int err = errno;
  1530. if (SCM_LIKELY (err == EINVAL))
  1531. /* The input byte sequence did not form a complete
  1532. character. Read another byte and try again. */
  1533. continue;
  1534. else
  1535. return err;
  1536. }
  1537. else
  1538. {
  1539. size_t output_size = sizeof (utf8_buf) - output_left;
  1540. if (SCM_LIKELY (output_size > 0))
  1541. {
  1542. /* iconv generated output. Convert the UTF8_BUF sequence
  1543. to a Unicode code point. */
  1544. *codepoint = utf8_to_codepoint (utf8_buf, output_size);
  1545. *len = input_size;
  1546. return 0;
  1547. }
  1548. else
  1549. {
  1550. /* iconv consumed some bytes without producing any output.
  1551. Most likely this means that a Unicode byte-order mark
  1552. (BOM) was consumed, which should not be included in the
  1553. returned buf. Shift any remaining bytes to the beginning
  1554. of buf, and continue the loop. */
  1555. memmove (buf, input, input_left);
  1556. input_size = input_left;
  1557. continue;
  1558. }
  1559. }
  1560. }
  1561. }
  1562. /* Read a codepoint from PORT and return it in *CODEPOINT. Fill BUF
  1563. with the byte representation of the codepoint in PORT's encoding, and
  1564. set *LEN to the length in bytes of that representation. Return 0 on
  1565. success and an errno value on error. */
  1566. static SCM_C_INLINE int
  1567. get_codepoint (SCM port, scm_t_wchar *codepoint,
  1568. char buf[SCM_MBCHAR_BUF_SIZE], size_t *len)
  1569. {
  1570. int err;
  1571. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  1572. scm_t_port_internal *pti = SCM_PORT_GET_INTERNAL (port);
  1573. if (pti->encoding_mode == SCM_PORT_ENCODING_MODE_UTF8)
  1574. err = get_utf8_codepoint (port, codepoint, (scm_t_uint8 *) buf, len);
  1575. else if (pti->encoding_mode == SCM_PORT_ENCODING_MODE_LATIN1)
  1576. err = get_latin1_codepoint (port, codepoint, buf, len);
  1577. else
  1578. err = get_iconv_codepoint (port, codepoint, buf, len);
  1579. if (SCM_LIKELY (err == 0))
  1580. {
  1581. if (SCM_UNLIKELY (pti->at_stream_start_for_bom_read))
  1582. {
  1583. /* Record that we're no longer at stream start. */
  1584. pti->at_stream_start_for_bom_read = 0;
  1585. if (pt->rw_random)
  1586. pti->at_stream_start_for_bom_write = 0;
  1587. /* If we just read a BOM in an encoding that recognizes them,
  1588. then silently consume it and read another code point. */
  1589. if (SCM_UNLIKELY
  1590. (*codepoint == SCM_UNICODE_BOM
  1591. && (pti->encoding_mode == SCM_PORT_ENCODING_MODE_UTF8
  1592. || strcmp (pt->encoding, "UTF-16") == 0
  1593. || strcmp (pt->encoding, "UTF-32") == 0)))
  1594. return get_codepoint (port, codepoint, buf, len);
  1595. }
  1596. update_port_lf (*codepoint, port);
  1597. }
  1598. else if (pt->ilseq_handler == SCM_ICONVEH_QUESTION_MARK)
  1599. {
  1600. *codepoint = '?';
  1601. err = 0;
  1602. update_port_lf (*codepoint, port);
  1603. }
  1604. return err;
  1605. }
  1606. /* Read a codepoint from PORT and return it. */
  1607. scm_t_wchar
  1608. scm_getc_unlocked (SCM port)
  1609. #define FUNC_NAME "scm_getc"
  1610. {
  1611. int err;
  1612. size_t len;
  1613. scm_t_wchar codepoint;
  1614. char buf[SCM_MBCHAR_BUF_SIZE];
  1615. err = get_codepoint (port, &codepoint, buf, &len);
  1616. if (SCM_UNLIKELY (err != 0))
  1617. /* At this point PORT should point past the invalid encoding, as per
  1618. R6RS-lib Section 8.2.4. */
  1619. scm_decoding_error (FUNC_NAME, err, "input decoding error", port);
  1620. return codepoint;
  1621. }
  1622. #undef FUNC_NAME
  1623. scm_t_wchar
  1624. scm_getc (SCM port)
  1625. {
  1626. scm_i_pthread_mutex_t *lock;
  1627. scm_t_wchar ret;
  1628. scm_c_lock_port (port, &lock);
  1629. ret = scm_getc_unlocked (port);
  1630. if (lock)
  1631. scm_i_pthread_mutex_unlock (lock);
  1632. return ret;
  1633. }
  1634. SCM_DEFINE (scm_read_char, "read-char", 0, 1, 0,
  1635. (SCM port),
  1636. "Return the next character available from @var{port}, updating\n"
  1637. "@var{port} to point to the following character. If no more\n"
  1638. "characters are available, the end-of-file object is returned.\n"
  1639. "\n"
  1640. "When @var{port}'s data cannot be decoded according to its\n"
  1641. "character encoding, a @code{decoding-error} is raised and\n"
  1642. "@var{port} points past the erroneous byte sequence.\n")
  1643. #define FUNC_NAME s_scm_read_char
  1644. {
  1645. scm_t_wchar c;
  1646. if (SCM_UNBNDP (port))
  1647. port = scm_current_input_port ();
  1648. SCM_VALIDATE_OPINPORT (1, port);
  1649. c = scm_getc_unlocked (port);
  1650. if (EOF == c)
  1651. return SCM_EOF_VAL;
  1652. return SCM_MAKE_CHAR (c);
  1653. }
  1654. #undef FUNC_NAME
  1655. /* Pushback. */
  1656. static void
  1657. scm_i_unget_bytes_unlocked (const unsigned char *buf, size_t len, SCM port)
  1658. #define FUNC_NAME "scm_unget_bytes"
  1659. {
  1660. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  1661. size_t old_len, new_len;
  1662. scm_i_clear_pending_eof (port);
  1663. if (pt->read_buf != pt->putback_buf)
  1664. /* switch to the put-back buffer. */
  1665. {
  1666. if (pt->putback_buf == NULL)
  1667. {
  1668. pt->putback_buf_size = (len > SCM_INITIAL_PUTBACK_BUF_SIZE
  1669. ? len : SCM_INITIAL_PUTBACK_BUF_SIZE);
  1670. pt->putback_buf
  1671. = (unsigned char *) scm_gc_malloc_pointerless
  1672. (pt->putback_buf_size, "putback buffer");
  1673. }
  1674. pt->saved_read_buf = pt->read_buf;
  1675. pt->saved_read_pos = pt->read_pos;
  1676. pt->saved_read_end = pt->read_end;
  1677. pt->saved_read_buf_size = pt->read_buf_size;
  1678. /* Put read_pos at the end of the buffer, so that ungets will not
  1679. have to shift the buffer contents each time. */
  1680. pt->read_buf = pt->putback_buf;
  1681. pt->read_pos = pt->read_end = pt->putback_buf + pt->putback_buf_size;
  1682. pt->read_buf_size = pt->putback_buf_size;
  1683. }
  1684. old_len = pt->read_end - pt->read_pos;
  1685. new_len = old_len + len;
  1686. if (new_len > pt->read_buf_size)
  1687. /* The putback buffer needs to be enlarged. */
  1688. {
  1689. size_t new_buf_size;
  1690. unsigned char *new_buf, *new_end, *new_pos;
  1691. new_buf_size = pt->read_buf_size * 2;
  1692. if (new_buf_size < new_len)
  1693. new_buf_size = new_len;
  1694. new_buf = (unsigned char *)
  1695. scm_gc_malloc_pointerless (new_buf_size, "putback buffer");
  1696. /* Put the bytes at the end of the buffer, so that future
  1697. ungets won't need to shift the buffer. */
  1698. new_end = new_buf + new_buf_size;
  1699. new_pos = new_end - old_len;
  1700. memcpy (new_pos, pt->read_pos, old_len);
  1701. pt->read_buf = pt->putback_buf = new_buf;
  1702. pt->read_pos = new_pos;
  1703. pt->read_end = new_end;
  1704. pt->read_buf_size = pt->putback_buf_size = new_buf_size;
  1705. }
  1706. else if (pt->read_buf + len < pt->read_pos)
  1707. /* If needed, shift the existing buffer contents up.
  1708. This should not happen unless some external code
  1709. manipulates the putback buffer pointers. */
  1710. {
  1711. unsigned char *new_end = pt->read_buf + pt->read_buf_size;
  1712. unsigned char *new_pos = new_end - old_len;
  1713. memmove (new_pos, pt->read_pos, old_len);
  1714. pt->read_pos = new_pos;
  1715. pt->read_end = new_end;
  1716. }
  1717. /* Move read_pos back and copy the bytes there. */
  1718. pt->read_pos -= len;
  1719. memcpy (pt->read_buf + (pt->read_pos - pt->read_buf), buf, len);
  1720. if (pt->rw_active == SCM_PORT_WRITE)
  1721. scm_flush (port);
  1722. if (pt->rw_random)
  1723. pt->rw_active = SCM_PORT_READ;
  1724. }
  1725. #undef FUNC_NAME
  1726. void
  1727. scm_unget_bytes_unlocked (const unsigned char *buf, size_t len, SCM port)
  1728. {
  1729. scm_i_unget_bytes_unlocked (buf, len, port);
  1730. }
  1731. void
  1732. scm_unget_byte_unlocked (int c, SCM port)
  1733. {
  1734. unsigned char byte = c;
  1735. scm_i_unget_bytes_unlocked (&byte, 1, port);
  1736. }
  1737. void
  1738. scm_unget_bytes (const unsigned char *buf, size_t len, SCM port)
  1739. {
  1740. scm_i_pthread_mutex_t *lock;
  1741. scm_c_lock_port (port, &lock);
  1742. scm_i_unget_bytes_unlocked (buf, len, port);
  1743. if (lock)
  1744. scm_i_pthread_mutex_unlock (lock);
  1745. }
  1746. void
  1747. scm_unget_byte (int c, SCM port)
  1748. {
  1749. unsigned char byte = c;
  1750. scm_i_pthread_mutex_t *lock;
  1751. scm_c_lock_port (port, &lock);
  1752. scm_i_unget_bytes_unlocked (&byte, 1, port);
  1753. if (lock)
  1754. scm_i_pthread_mutex_unlock (lock);
  1755. }
  1756. void
  1757. scm_ungetc_unlocked (scm_t_wchar c, SCM port)
  1758. #define FUNC_NAME "scm_ungetc"
  1759. {
  1760. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  1761. scm_t_port_internal *pti = SCM_PORT_GET_INTERNAL (port);
  1762. char *result;
  1763. char result_buf[10];
  1764. size_t len;
  1765. len = sizeof (result_buf);
  1766. if (pti->encoding_mode == SCM_PORT_ENCODING_MODE_UTF8)
  1767. {
  1768. if (c < 0xf0)
  1769. {
  1770. result_buf[0] = (char) c;
  1771. result = result_buf;
  1772. len = 1;
  1773. }
  1774. else
  1775. result =
  1776. (char *) u32_to_u8 ((uint32_t *) &c, 1, (uint8_t *) result_buf, &len);
  1777. }
  1778. else if (pti->encoding_mode == SCM_PORT_ENCODING_MODE_LATIN1 && c <= 0xff)
  1779. {
  1780. result_buf[0] = (char) c;
  1781. result = result_buf;
  1782. len = 1;
  1783. }
  1784. else
  1785. result = u32_conv_to_encoding (pt->encoding,
  1786. (enum iconv_ilseq_handler) pt->ilseq_handler,
  1787. (uint32_t *) &c, 1, NULL,
  1788. result_buf, &len);
  1789. if (SCM_UNLIKELY (result == NULL || len == 0))
  1790. scm_encoding_error (FUNC_NAME, errno,
  1791. "conversion to port encoding failed",
  1792. SCM_BOOL_F, SCM_MAKE_CHAR (c));
  1793. scm_i_unget_bytes_unlocked ((unsigned char *) result, len, port);
  1794. if (SCM_UNLIKELY (result != result_buf))
  1795. free (result);
  1796. if (c == '\n')
  1797. {
  1798. /* What should col be in this case?
  1799. * We'll leave it at -1.
  1800. */
  1801. SCM_LINUM (port) -= 1;
  1802. }
  1803. else
  1804. SCM_COL(port) -= 1;
  1805. }
  1806. #undef FUNC_NAME
  1807. void
  1808. scm_ungetc (scm_t_wchar c, SCM port)
  1809. {
  1810. scm_i_pthread_mutex_t *lock;
  1811. scm_c_lock_port (port, &lock);
  1812. scm_ungetc_unlocked (c, port);
  1813. if (lock)
  1814. scm_i_pthread_mutex_unlock (lock);
  1815. }
  1816. void
  1817. scm_ungets_unlocked (const char *s, int n, SCM port)
  1818. {
  1819. /* This is simple minded and inefficient, but unreading strings is
  1820. * probably not a common operation, and remember that line and
  1821. * column numbers have to be handled...
  1822. *
  1823. * Please feel free to write an optimized version!
  1824. */
  1825. while (n--)
  1826. scm_ungetc_unlocked (s[n], port);
  1827. }
  1828. void
  1829. scm_ungets (const char *s, int n, SCM port)
  1830. {
  1831. scm_i_pthread_mutex_t *lock;
  1832. scm_c_lock_port (port, &lock);
  1833. scm_ungets_unlocked (s, n, port);
  1834. if (lock)
  1835. scm_i_pthread_mutex_unlock (lock);
  1836. }
  1837. SCM_DEFINE (scm_peek_char, "peek-char", 0, 1, 0,
  1838. (SCM port),
  1839. "Return the next character available from @var{port},\n"
  1840. "@emph{without} updating @var{port} to point to the following\n"
  1841. "character. If no more characters are available, the\n"
  1842. "end-of-file object is returned.\n"
  1843. "\n"
  1844. "The value returned by\n"
  1845. "a call to @code{peek-char} is the same as the value that would\n"
  1846. "have been returned by a call to @code{read-char} on the same\n"
  1847. "port. The only difference is that the very next call to\n"
  1848. "@code{read-char} or @code{peek-char} on that @var{port} will\n"
  1849. "return the value returned by the preceding call to\n"
  1850. "@code{peek-char}. In particular, a call to @code{peek-char} on\n"
  1851. "an interactive port will hang waiting for input whenever a call\n"
  1852. "to @code{read-char} would have hung.\n"
  1853. "\n"
  1854. "As for @code{read-char}, a @code{decoding-error} may be raised\n"
  1855. "if such a situation occurs. However, unlike with @code{read-char},\n"
  1856. "@var{port} still points at the beginning of the erroneous byte\n"
  1857. "sequence when the error is raised.\n")
  1858. #define FUNC_NAME s_scm_peek_char
  1859. {
  1860. int err;
  1861. SCM result;
  1862. scm_t_wchar c;
  1863. char bytes[SCM_MBCHAR_BUF_SIZE];
  1864. long column, line;
  1865. size_t len = 0;
  1866. if (SCM_UNBNDP (port))
  1867. port = scm_current_input_port ();
  1868. SCM_VALIDATE_OPINPORT (1, port);
  1869. column = SCM_COL (port);
  1870. line = SCM_LINUM (port);
  1871. err = get_codepoint (port, &c, bytes, &len);
  1872. scm_i_unget_bytes_unlocked ((unsigned char *) bytes, len, port);
  1873. SCM_COL (port) = column;
  1874. SCM_LINUM (port) = line;
  1875. if (SCM_UNLIKELY (err != 0))
  1876. {
  1877. scm_decoding_error (FUNC_NAME, err, "input decoding error", port);
  1878. /* Shouldn't happen since `catch' always aborts to prompt. */
  1879. result = SCM_BOOL_F;
  1880. }
  1881. else if (c == EOF)
  1882. {
  1883. scm_i_set_pending_eof (port);
  1884. result = SCM_EOF_VAL;
  1885. }
  1886. else
  1887. result = SCM_MAKE_CHAR (c);
  1888. return result;
  1889. }
  1890. #undef FUNC_NAME
  1891. SCM_DEFINE (scm_unread_char, "unread-char", 1, 1, 0,
  1892. (SCM cobj, SCM port),
  1893. "Place character @var{cobj} in @var{port} so that it will be\n"
  1894. "read by the next read operation. If called multiple times, the\n"
  1895. "unread characters will be read again in last-in first-out\n"
  1896. "order. If @var{port} is not supplied, the current input port\n"
  1897. "is used.")
  1898. #define FUNC_NAME s_scm_unread_char
  1899. {
  1900. int c;
  1901. SCM_VALIDATE_CHAR (1, cobj);
  1902. if (SCM_UNBNDP (port))
  1903. port = scm_current_input_port ();
  1904. SCM_VALIDATE_OPINPORT (2, port);
  1905. c = SCM_CHAR (cobj);
  1906. scm_ungetc_unlocked (c, port);
  1907. return cobj;
  1908. }
  1909. #undef FUNC_NAME
  1910. SCM_DEFINE (scm_unread_string, "unread-string", 2, 0, 0,
  1911. (SCM str, SCM port),
  1912. "Place the string @var{str} in @var{port} so that its characters will be\n"
  1913. "read in subsequent read operations. If called multiple times, the\n"
  1914. "unread characters will be read again in last-in first-out order. If\n"
  1915. "@var{port} is not supplied, the current-input-port is used.")
  1916. #define FUNC_NAME s_scm_unread_string
  1917. {
  1918. int n;
  1919. SCM_VALIDATE_STRING (1, str);
  1920. if (SCM_UNBNDP (port))
  1921. port = scm_current_input_port ();
  1922. SCM_VALIDATE_OPINPORT (2, port);
  1923. n = scm_i_string_length (str);
  1924. while (n--)
  1925. scm_ungetc_unlocked (scm_i_string_ref (str, n), port);
  1926. return str;
  1927. }
  1928. #undef FUNC_NAME
  1929. /* Manipulating the buffers. */
  1930. /* This routine does not take any locks, as it is usually called as part
  1931. of a port implementation. */
  1932. void
  1933. scm_port_non_buffer (scm_t_port *pt)
  1934. {
  1935. pt->read_pos = pt->read_buf = pt->read_end = &pt->shortbuf;
  1936. pt->write_buf = pt->write_pos = &pt->shortbuf;
  1937. pt->read_buf_size = pt->write_buf_size = 1;
  1938. pt->write_end = pt->write_buf + pt->write_buf_size;
  1939. }
  1940. /* this should only be called when the read buffer is empty. it
  1941. tries to refill the read buffer. it returns the first char from
  1942. the port, which is either EOF or *(pt->read_pos). */
  1943. static int
  1944. scm_i_fill_input_unlocked (SCM port)
  1945. {
  1946. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  1947. scm_t_port_internal *pti = SCM_PORT_GET_INTERNAL (port);
  1948. assert (pt->read_pos == pt->read_end);
  1949. if (pti->pending_eof)
  1950. {
  1951. pti->pending_eof = 0;
  1952. return EOF;
  1953. }
  1954. if (pt->read_buf == pt->putback_buf)
  1955. {
  1956. /* finished reading put-back chars. */
  1957. pt->read_buf = pt->saved_read_buf;
  1958. pt->read_pos = pt->saved_read_pos;
  1959. pt->read_end = pt->saved_read_end;
  1960. pt->read_buf_size = pt->saved_read_buf_size;
  1961. if (pt->read_pos < pt->read_end)
  1962. return *(pt->read_pos);
  1963. }
  1964. return SCM_PORT_DESCRIPTOR (port)->fill_input (port);
  1965. }
  1966. int
  1967. scm_fill_input (SCM port)
  1968. {
  1969. scm_i_pthread_mutex_t *lock;
  1970. int ret;
  1971. scm_c_lock_port (port, &lock);
  1972. ret = scm_fill_input_unlocked (port);
  1973. if (lock)
  1974. scm_i_pthread_mutex_unlock (lock);
  1975. return ret;
  1976. }
  1977. /* Slow-path fallback for 'scm_get_byte_or_eof_unlocked' */
  1978. int
  1979. scm_slow_get_byte_or_eof_unlocked (SCM port)
  1980. {
  1981. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  1982. if (pt->rw_active == SCM_PORT_WRITE)
  1983. scm_flush_unlocked (port);
  1984. if (pt->rw_random)
  1985. pt->rw_active = SCM_PORT_READ;
  1986. if (pt->read_pos >= pt->read_end)
  1987. {
  1988. if (SCM_UNLIKELY (scm_i_fill_input_unlocked (port) == EOF))
  1989. return EOF;
  1990. }
  1991. return *pt->read_pos++;
  1992. }
  1993. /* Slow-path fallback for 'scm_peek_byte_or_eof_unlocked' */
  1994. int
  1995. scm_slow_peek_byte_or_eof_unlocked (SCM port)
  1996. {
  1997. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  1998. if (pt->rw_active == SCM_PORT_WRITE)
  1999. scm_flush_unlocked (port);
  2000. if (pt->rw_random)
  2001. pt->rw_active = SCM_PORT_READ;
  2002. if (pt->read_pos >= pt->read_end)
  2003. {
  2004. if (SCM_UNLIKELY (scm_i_fill_input_unlocked (port) == EOF))
  2005. {
  2006. scm_i_set_pending_eof (port);
  2007. return EOF;
  2008. }
  2009. }
  2010. return *pt->read_pos;
  2011. }
  2012. /* Move up to READ_LEN bytes from PORT's putback and/or read buffers
  2013. into memory starting at DEST. Return the number of bytes moved.
  2014. PORT's line/column numbers are left unchanged. */
  2015. size_t
  2016. scm_take_from_input_buffers (SCM port, char *dest, size_t read_len)
  2017. {
  2018. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  2019. size_t bytes_read = 0;
  2020. size_t from_buf = min (pt->read_end - pt->read_pos, read_len);
  2021. if (from_buf > 0)
  2022. {
  2023. memcpy (dest, pt->read_pos, from_buf);
  2024. pt->read_pos += from_buf;
  2025. bytes_read += from_buf;
  2026. read_len -= from_buf;
  2027. dest += from_buf;
  2028. }
  2029. /* if putback was active, try the real input buffer too. */
  2030. if (pt->read_buf == pt->putback_buf)
  2031. {
  2032. from_buf = min (pt->saved_read_end - pt->saved_read_pos, read_len);
  2033. if (from_buf > 0)
  2034. {
  2035. memcpy (dest, pt->saved_read_pos, from_buf);
  2036. pt->saved_read_pos += from_buf;
  2037. bytes_read += from_buf;
  2038. }
  2039. }
  2040. return bytes_read;
  2041. }
  2042. /* Clear a port's read buffers, returning the contents. */
  2043. SCM_DEFINE (scm_drain_input, "drain-input", 1, 0, 0,
  2044. (SCM port),
  2045. "This procedure clears a port's input buffers, similar\n"
  2046. "to the way that force-output clears the output buffer. The\n"
  2047. "contents of the buffers are returned as a single string, e.g.,\n"
  2048. "\n"
  2049. "@lisp\n"
  2050. "(define p (open-input-file ...))\n"
  2051. "(drain-input p) => empty string, nothing buffered yet.\n"
  2052. "(unread-char (read-char p) p)\n"
  2053. "(drain-input p) => initial chars from p, up to the buffer size.\n"
  2054. "@end lisp\n\n"
  2055. "Draining the buffers may be useful for cleanly finishing\n"
  2056. "buffered I/O so that the file descriptor can be used directly\n"
  2057. "for further input.")
  2058. #define FUNC_NAME s_scm_drain_input
  2059. {
  2060. SCM result;
  2061. char *data;
  2062. scm_t_port *pt;
  2063. long count;
  2064. SCM_VALIDATE_OPINPORT (1, port);
  2065. pt = SCM_PTAB_ENTRY (port);
  2066. count = pt->read_end - pt->read_pos;
  2067. if (pt->read_buf == pt->putback_buf)
  2068. count += pt->saved_read_end - pt->saved_read_pos;
  2069. if (count)
  2070. {
  2071. result = scm_i_make_string (count, &data, 0);
  2072. scm_take_from_input_buffers (port, data, count);
  2073. }
  2074. else
  2075. result = scm_nullstr;
  2076. return result;
  2077. }
  2078. #undef FUNC_NAME
  2079. void
  2080. scm_end_input_unlocked (SCM port)
  2081. {
  2082. long offset;
  2083. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  2084. scm_i_clear_pending_eof (port);
  2085. if (pt->read_buf == pt->putback_buf)
  2086. {
  2087. offset = pt->read_end - pt->read_pos;
  2088. pt->read_buf = pt->saved_read_buf;
  2089. pt->read_pos = pt->saved_read_pos;
  2090. pt->read_end = pt->saved_read_end;
  2091. pt->read_buf_size = pt->saved_read_buf_size;
  2092. }
  2093. else
  2094. offset = 0;
  2095. SCM_PORT_DESCRIPTOR (port)->end_input (port, offset);
  2096. }
  2097. void
  2098. scm_end_input (SCM port)
  2099. {
  2100. scm_i_pthread_mutex_t *lock;
  2101. scm_c_lock_port (port, &lock);
  2102. scm_end_input_unlocked (port);
  2103. if (lock)
  2104. scm_i_pthread_mutex_unlock (lock);
  2105. }
  2106. SCM_DEFINE (scm_force_output, "force-output", 0, 1, 0,
  2107. (SCM port),
  2108. "Flush the specified output port, or the current output port if @var{port}\n"
  2109. "is omitted. The current output buffer contents are passed to the\n"
  2110. "underlying port implementation (e.g., in the case of fports, the\n"
  2111. "data will be written to the file and the output buffer will be cleared.)\n"
  2112. "It has no effect on an unbuffered port.\n\n"
  2113. "The return value is unspecified.")
  2114. #define FUNC_NAME s_scm_force_output
  2115. {
  2116. if (SCM_UNBNDP (port))
  2117. port = scm_current_output_port ();
  2118. else
  2119. {
  2120. port = SCM_COERCE_OUTPORT (port);
  2121. SCM_VALIDATE_OPOUTPORT (1, port);
  2122. }
  2123. scm_flush_unlocked (port);
  2124. return SCM_UNSPECIFIED;
  2125. }
  2126. #undef FUNC_NAME
  2127. void
  2128. scm_flush_unlocked (SCM port)
  2129. {
  2130. SCM_PORT_DESCRIPTOR (port)->flush (port);
  2131. }
  2132. void
  2133. scm_flush (SCM port)
  2134. {
  2135. scm_i_pthread_mutex_t *lock;
  2136. scm_c_lock_port (port, &lock);
  2137. scm_flush_unlocked (port);
  2138. if (lock)
  2139. scm_i_pthread_mutex_unlock (lock);
  2140. }
  2141. int
  2142. scm_fill_input_unlocked (SCM port)
  2143. {
  2144. return scm_i_fill_input_unlocked (port);
  2145. }
  2146. /* Output. */
  2147. void
  2148. scm_putc (char c, SCM port)
  2149. {
  2150. scm_i_pthread_mutex_t *lock;
  2151. scm_c_lock_port (port, &lock);
  2152. scm_putc_unlocked (c, port);
  2153. if (lock)
  2154. scm_i_pthread_mutex_unlock (lock);
  2155. }
  2156. void
  2157. scm_puts (const char *s, SCM port)
  2158. {
  2159. scm_i_pthread_mutex_t *lock;
  2160. scm_c_lock_port (port, &lock);
  2161. scm_puts_unlocked (s, port);
  2162. if (lock)
  2163. scm_i_pthread_mutex_unlock (lock);
  2164. }
  2165. /* scm_c_write
  2166. *
  2167. * Used by an application to write arbitrary number of bytes to an SCM
  2168. * port. Similar semantics as libc write. However, unlike libc
  2169. * write, scm_c_write writes the requested number of bytes and has no
  2170. * return value.
  2171. *
  2172. * Warning: Doesn't update port line and column counts!
  2173. */
  2174. void
  2175. scm_c_write_unlocked (SCM port, const void *ptr, size_t size)
  2176. #define FUNC_NAME "scm_c_write"
  2177. {
  2178. scm_t_port *pt;
  2179. scm_t_ptob_descriptor *ptob;
  2180. SCM_VALIDATE_OPOUTPORT (1, port);
  2181. pt = SCM_PTAB_ENTRY (port);
  2182. ptob = SCM_PORT_DESCRIPTOR (port);
  2183. if (pt->rw_active == SCM_PORT_READ)
  2184. scm_end_input_unlocked (port);
  2185. ptob->write (port, ptr, size);
  2186. if (pt->rw_random)
  2187. pt->rw_active = SCM_PORT_WRITE;
  2188. }
  2189. #undef FUNC_NAME
  2190. void
  2191. scm_c_write (SCM port, const void *ptr, size_t size)
  2192. {
  2193. scm_i_pthread_mutex_t *lock;
  2194. scm_c_lock_port (port, &lock);
  2195. scm_c_write_unlocked (port, ptr, size);
  2196. if (lock)
  2197. scm_i_pthread_mutex_unlock (lock);
  2198. }
  2199. /* scm_lfwrite
  2200. *
  2201. * This function differs from scm_c_write; it updates port line and
  2202. * column. */
  2203. void
  2204. scm_lfwrite_unlocked (const char *ptr, size_t size, SCM port)
  2205. {
  2206. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  2207. scm_t_ptob_descriptor *ptob = SCM_PORT_DESCRIPTOR (port);
  2208. if (pt->rw_active == SCM_PORT_READ)
  2209. scm_end_input_unlocked (port);
  2210. ptob->write (port, ptr, size);
  2211. for (; size; ptr++, size--)
  2212. update_port_lf ((scm_t_wchar) (unsigned char) *ptr, port);
  2213. if (pt->rw_random)
  2214. pt->rw_active = SCM_PORT_WRITE;
  2215. }
  2216. void
  2217. scm_lfwrite (const char *ptr, size_t size, SCM port)
  2218. {
  2219. scm_i_pthread_mutex_t *lock;
  2220. scm_c_lock_port (port, &lock);
  2221. scm_lfwrite_unlocked (ptr, size, port);
  2222. if (lock)
  2223. scm_i_pthread_mutex_unlock (lock);
  2224. }
  2225. /* Write STR to PORT from START inclusive to END exclusive. */
  2226. void
  2227. scm_lfwrite_substr (SCM str, size_t start, size_t end, SCM port)
  2228. {
  2229. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  2230. if (pt->rw_active == SCM_PORT_READ)
  2231. scm_end_input_unlocked (port);
  2232. if (end == (size_t) -1)
  2233. end = scm_i_string_length (str);
  2234. scm_i_display_substring (str, start, end, port);
  2235. if (pt->rw_random)
  2236. pt->rw_active = SCM_PORT_WRITE;
  2237. }
  2238. /* Querying and setting positions, and character availability. */
  2239. SCM_DEFINE (scm_char_ready_p, "char-ready?", 0, 1, 0,
  2240. (SCM port),
  2241. "Return @code{#t} if a character is ready on input @var{port}\n"
  2242. "and return @code{#f} otherwise. If @code{char-ready?} returns\n"
  2243. "@code{#t} then the next @code{read-char} operation on\n"
  2244. "@var{port} is guaranteed not to hang. If @var{port} is a file\n"
  2245. "port at end of file then @code{char-ready?} returns @code{#t}.\n"
  2246. "\n"
  2247. "@code{char-ready?} exists to make it possible for a\n"
  2248. "program to accept characters from interactive ports without\n"
  2249. "getting stuck waiting for input. Any input editors associated\n"
  2250. "with such ports must make sure that characters whose existence\n"
  2251. "has been asserted by @code{char-ready?} cannot be rubbed out.\n"
  2252. "If @code{char-ready?} were to return @code{#f} at end of file,\n"
  2253. "a port at end of file would be indistinguishable from an\n"
  2254. "interactive port that has no ready characters.")
  2255. #define FUNC_NAME s_scm_char_ready_p
  2256. {
  2257. scm_t_port *pt;
  2258. if (SCM_UNBNDP (port))
  2259. port = scm_current_input_port ();
  2260. /* It's possible to close the current input port, so validate even in
  2261. this case. */
  2262. SCM_VALIDATE_OPINPORT (1, port);
  2263. pt = SCM_PTAB_ENTRY (port);
  2264. /* if the current read buffer is filled, or the
  2265. last pushed-back char has been read and the saved buffer is
  2266. filled, result is true. */
  2267. if (pt->read_pos < pt->read_end
  2268. || (pt->read_buf == pt->putback_buf
  2269. && pt->saved_read_pos < pt->saved_read_end))
  2270. return SCM_BOOL_T;
  2271. else
  2272. {
  2273. scm_t_ptob_descriptor *ptob = SCM_PORT_DESCRIPTOR (port);
  2274. if (ptob->input_waiting)
  2275. return scm_from_bool(ptob->input_waiting (port));
  2276. else
  2277. return SCM_BOOL_T;
  2278. }
  2279. }
  2280. #undef FUNC_NAME
  2281. SCM_DEFINE (scm_seek, "seek", 3, 0, 0,
  2282. (SCM fd_port, SCM offset, SCM whence),
  2283. "Sets the current position of @var{fd_port} to the integer\n"
  2284. "@var{offset}, which is interpreted according to the value of\n"
  2285. "@var{whence}.\n"
  2286. "\n"
  2287. "One of the following variables should be supplied for\n"
  2288. "@var{whence}:\n"
  2289. "@defvar SEEK_SET\n"
  2290. "Seek from the beginning of the file.\n"
  2291. "@end defvar\n"
  2292. "@defvar SEEK_CUR\n"
  2293. "Seek from the current position.\n"
  2294. "@end defvar\n"
  2295. "@defvar SEEK_END\n"
  2296. "Seek from the end of the file.\n"
  2297. "@end defvar\n"
  2298. "If @var{fd_port} is a file descriptor, the underlying system\n"
  2299. "call is @code{lseek}. @var{port} may be a string port.\n"
  2300. "\n"
  2301. "The value returned is the new position in the file. This means\n"
  2302. "that the current position of a port can be obtained using:\n"
  2303. "@lisp\n"
  2304. "(seek port 0 SEEK_CUR)\n"
  2305. "@end lisp")
  2306. #define FUNC_NAME s_scm_seek
  2307. {
  2308. int how;
  2309. fd_port = SCM_COERCE_OUTPORT (fd_port);
  2310. how = scm_to_int (whence);
  2311. if (how != SEEK_SET && how != SEEK_CUR && how != SEEK_END)
  2312. SCM_OUT_OF_RANGE (3, whence);
  2313. if (SCM_OPPORTP (fd_port))
  2314. {
  2315. scm_t_port_internal *pti = SCM_PORT_GET_INTERNAL (fd_port);
  2316. scm_t_ptob_descriptor *ptob = SCM_PORT_DESCRIPTOR (fd_port);
  2317. off_t_or_off64_t off = scm_to_off_t_or_off64_t (offset);
  2318. off_t_or_off64_t rv;
  2319. if (!ptob->seek)
  2320. SCM_MISC_ERROR ("port is not seekable",
  2321. scm_cons (fd_port, SCM_EOL));
  2322. else
  2323. rv = ptob->seek (fd_port, off, how);
  2324. /* Set stream-start flags according to new position. */
  2325. pti->at_stream_start_for_bom_read = (rv == 0);
  2326. pti->at_stream_start_for_bom_write = (rv == 0);
  2327. scm_i_clear_pending_eof (fd_port);
  2328. return scm_from_off_t_or_off64_t (rv);
  2329. }
  2330. else /* file descriptor?. */
  2331. {
  2332. off_t_or_off64_t off = scm_to_off_t_or_off64_t (offset);
  2333. off_t_or_off64_t rv;
  2334. rv = lseek_or_lseek64 (scm_to_int (fd_port), off, how);
  2335. if (rv == -1)
  2336. SCM_SYSERROR;
  2337. return scm_from_off_t_or_off64_t (rv);
  2338. }
  2339. }
  2340. #undef FUNC_NAME
  2341. #ifndef O_BINARY
  2342. #define O_BINARY 0
  2343. #endif
  2344. /* Mingw has ftruncate(), perhaps implemented above using chsize, but
  2345. doesn't have the filename version truncate(), hence this code. */
  2346. #if HAVE_FTRUNCATE && ! HAVE_TRUNCATE
  2347. static int
  2348. truncate (const char *file, off_t length)
  2349. {
  2350. int ret, fdes;
  2351. fdes = open (file, O_BINARY | O_WRONLY);
  2352. if (fdes == -1)
  2353. return -1;
  2354. ret = ftruncate (fdes, length);
  2355. if (ret == -1)
  2356. {
  2357. int save_errno = errno;
  2358. close (fdes);
  2359. errno = save_errno;
  2360. return -1;
  2361. }
  2362. return close (fdes);
  2363. }
  2364. #endif /* HAVE_FTRUNCATE && ! HAVE_TRUNCATE */
  2365. SCM_DEFINE (scm_truncate_file, "truncate-file", 1, 1, 0,
  2366. (SCM object, SCM length),
  2367. "Truncate file @var{object} to @var{length} bytes. @var{object}\n"
  2368. "can be a filename string, a port object, or an integer file\n"
  2369. "descriptor.\n"
  2370. "The return value is unspecified.\n"
  2371. "\n"
  2372. "For a port or file descriptor @var{length} can be omitted, in\n"
  2373. "which case the file is truncated at the current position (per\n"
  2374. "@code{ftell} above).\n"
  2375. "\n"
  2376. "On most systems a file can be extended by giving a length\n"
  2377. "greater than the current size, but this is not mandatory in the\n"
  2378. "POSIX standard.")
  2379. #define FUNC_NAME s_scm_truncate_file
  2380. {
  2381. int rv;
  2382. /* "object" can be a port, fdes or filename.
  2383. Negative "length" makes no sense, but it's left to truncate() or
  2384. ftruncate() to give back an error for that (normally EINVAL).
  2385. */
  2386. if (SCM_UNBNDP (length))
  2387. {
  2388. /* must supply length if object is a filename. */
  2389. if (scm_is_string (object))
  2390. SCM_MISC_ERROR("must supply length if OBJECT is a filename", SCM_EOL);
  2391. length = scm_seek (object, SCM_INUM0, scm_from_int (SEEK_CUR));
  2392. }
  2393. object = SCM_COERCE_OUTPORT (object);
  2394. if (scm_is_integer (object))
  2395. {
  2396. off_t_or_off64_t c_length = scm_to_off_t_or_off64_t (length);
  2397. SCM_SYSCALL (rv = ftruncate_or_ftruncate64 (scm_to_int (object),
  2398. c_length));
  2399. }
  2400. else if (SCM_OPOUTPORTP (object))
  2401. {
  2402. off_t_or_off64_t c_length = scm_to_off_t_or_off64_t (length);
  2403. scm_t_port *pt = SCM_PTAB_ENTRY (object);
  2404. scm_t_ptob_descriptor *ptob = SCM_PORT_DESCRIPTOR (object);
  2405. if (!ptob->truncate)
  2406. SCM_MISC_ERROR ("port is not truncatable", SCM_EOL);
  2407. scm_i_clear_pending_eof (object);
  2408. if (pt->rw_active == SCM_PORT_READ)
  2409. scm_end_input_unlocked (object);
  2410. else if (pt->rw_active == SCM_PORT_WRITE)
  2411. ptob->flush (object);
  2412. ptob->truncate (object, c_length);
  2413. rv = 0;
  2414. }
  2415. else
  2416. {
  2417. off_t_or_off64_t c_length = scm_to_off_t_or_off64_t (length);
  2418. char *str = scm_to_locale_string (object);
  2419. int eno;
  2420. SCM_SYSCALL (rv = truncate_or_truncate64 (str, c_length));
  2421. eno = errno;
  2422. free (str);
  2423. errno = eno;
  2424. }
  2425. if (rv == -1)
  2426. SCM_SYSERROR;
  2427. return SCM_UNSPECIFIED;
  2428. }
  2429. #undef FUNC_NAME
  2430. SCM_DEFINE (scm_port_line, "port-line", 1, 0, 0,
  2431. (SCM port),
  2432. "Return the current line number for @var{port}.\n"
  2433. "\n"
  2434. "The first line of a file is 0. But you might want to add 1\n"
  2435. "when printing line numbers, since starting from 1 is\n"
  2436. "traditional in error messages, and likely to be more natural to\n"
  2437. "non-programmers.")
  2438. #define FUNC_NAME s_scm_port_line
  2439. {
  2440. port = SCM_COERCE_OUTPORT (port);
  2441. SCM_VALIDATE_OPENPORT (1, port);
  2442. return scm_from_long (SCM_LINUM (port));
  2443. }
  2444. #undef FUNC_NAME
  2445. SCM_DEFINE (scm_set_port_line_x, "set-port-line!", 2, 0, 0,
  2446. (SCM port, SCM line),
  2447. "Set the current line number for @var{port} to @var{line}. The\n"
  2448. "first line of a file is 0.")
  2449. #define FUNC_NAME s_scm_set_port_line_x
  2450. {
  2451. port = SCM_COERCE_OUTPORT (port);
  2452. SCM_VALIDATE_OPENPORT (1, port);
  2453. SCM_PTAB_ENTRY (port)->line_number = scm_to_long (line);
  2454. return SCM_UNSPECIFIED;
  2455. }
  2456. #undef FUNC_NAME
  2457. SCM_DEFINE (scm_port_column, "port-column", 1, 0, 0,
  2458. (SCM port),
  2459. "Return the current column number of @var{port}.\n"
  2460. "If the number is\n"
  2461. "unknown, the result is #f. Otherwise, the result is a 0-origin integer\n"
  2462. "- i.e. the first character of the first line is line 0, column 0.\n"
  2463. "(However, when you display a file position, for example in an error\n"
  2464. "message, we recommend you add 1 to get 1-origin integers. This is\n"
  2465. "because lines and column numbers traditionally start with 1, and that is\n"
  2466. "what non-programmers will find most natural.)")
  2467. #define FUNC_NAME s_scm_port_column
  2468. {
  2469. port = SCM_COERCE_OUTPORT (port);
  2470. SCM_VALIDATE_OPENPORT (1, port);
  2471. return scm_from_int (SCM_COL (port));
  2472. }
  2473. #undef FUNC_NAME
  2474. SCM_DEFINE (scm_set_port_column_x, "set-port-column!", 2, 0, 0,
  2475. (SCM port, SCM column),
  2476. "Set the current column of @var{port}. Before reading the first\n"
  2477. "character on a line the column should be 0.")
  2478. #define FUNC_NAME s_scm_set_port_column_x
  2479. {
  2480. port = SCM_COERCE_OUTPORT (port);
  2481. SCM_VALIDATE_OPENPORT (1, port);
  2482. SCM_PTAB_ENTRY (port)->column_number = scm_to_int (column);
  2483. return SCM_UNSPECIFIED;
  2484. }
  2485. #undef FUNC_NAME
  2486. SCM_DEFINE (scm_port_filename, "port-filename", 1, 0, 0,
  2487. (SCM port),
  2488. "Return the filename associated with @var{port}, or @code{#f}\n"
  2489. "if no filename is associated with the port.")
  2490. #define FUNC_NAME s_scm_port_filename
  2491. {
  2492. port = SCM_COERCE_OUTPORT (port);
  2493. SCM_VALIDATE_OPENPORT (1, port);
  2494. return SCM_FILENAME (port);
  2495. }
  2496. #undef FUNC_NAME
  2497. SCM_DEFINE (scm_set_port_filename_x, "set-port-filename!", 2, 0, 0,
  2498. (SCM port, SCM filename),
  2499. "Change the filename associated with @var{port}, using the current input\n"
  2500. "port if none is specified. Note that this does not change the port's\n"
  2501. "source of data, but only the value that is returned by\n"
  2502. "@code{port-filename} and reported in diagnostic output.")
  2503. #define FUNC_NAME s_scm_set_port_filename_x
  2504. {
  2505. port = SCM_COERCE_OUTPORT (port);
  2506. SCM_VALIDATE_OPENPORT (1, port);
  2507. /* We allow the user to set the filename to whatever he likes. */
  2508. SCM_SET_FILENAME (port, filename);
  2509. return SCM_UNSPECIFIED;
  2510. }
  2511. #undef FUNC_NAME
  2512. /* Implementation helpers for port printing functions. */
  2513. void
  2514. scm_print_port_mode (SCM exp, SCM port)
  2515. {
  2516. scm_puts_unlocked (SCM_CLOSEDP (exp)
  2517. ? "closed: "
  2518. : (SCM_RDNG & SCM_CELL_WORD_0 (exp)
  2519. ? (SCM_WRTNG & SCM_CELL_WORD_0 (exp)
  2520. ? "input-output: "
  2521. : "input: ")
  2522. : (SCM_WRTNG & SCM_CELL_WORD_0 (exp)
  2523. ? "output: "
  2524. : "bogus: ")),
  2525. port);
  2526. }
  2527. int
  2528. scm_port_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
  2529. {
  2530. char *type = SCM_PTOBNAME (SCM_PTOBNUM (exp));
  2531. if (!type)
  2532. type = "port";
  2533. scm_puts_unlocked ("#<", port);
  2534. scm_print_port_mode (exp, port);
  2535. scm_puts_unlocked (type, port);
  2536. scm_putc_unlocked (' ', port);
  2537. scm_uintprint (SCM_CELL_WORD_1 (exp), 16, port);
  2538. scm_putc_unlocked ('>', port);
  2539. return 1;
  2540. }
  2541. /* Iterating over all ports. */
  2542. struct for_each_data
  2543. {
  2544. void (*proc) (void *data, SCM p);
  2545. void *data;
  2546. };
  2547. static SCM
  2548. for_each_trampoline (void *data, SCM port, SCM result)
  2549. {
  2550. struct for_each_data *d = data;
  2551. d->proc (d->data, port);
  2552. return result;
  2553. }
  2554. void
  2555. scm_c_port_for_each (void (*proc)(void *data, SCM p), void *data)
  2556. {
  2557. struct for_each_data d;
  2558. d.proc = proc;
  2559. d.data = data;
  2560. scm_c_weak_set_fold (for_each_trampoline, &d, SCM_EOL,
  2561. scm_i_port_weak_set);
  2562. }
  2563. static void
  2564. scm_for_each_trampoline (void *data, SCM port)
  2565. {
  2566. scm_call_1 (SCM_PACK_POINTER (data), port);
  2567. }
  2568. SCM_DEFINE (scm_port_for_each, "port-for-each", 1, 0, 0,
  2569. (SCM proc),
  2570. "Apply @var{proc} to each port in the Guile port table\n"
  2571. "in turn. The return value is unspecified. More specifically,\n"
  2572. "@var{proc} is applied exactly once to every port that exists\n"
  2573. "in the system at the time @code{port-for-each} is invoked.\n"
  2574. "Changes to the port table while @code{port-for-each} is running\n"
  2575. "have no effect as far as @code{port-for-each} is concerned.")
  2576. #define FUNC_NAME s_scm_port_for_each
  2577. {
  2578. SCM_VALIDATE_PROC (1, proc);
  2579. scm_c_port_for_each (scm_for_each_trampoline, SCM_UNPACK_POINTER (proc));
  2580. return SCM_UNSPECIFIED;
  2581. }
  2582. #undef FUNC_NAME
  2583. static void
  2584. flush_output_port (void *closure, SCM port)
  2585. {
  2586. if (SCM_OPOUTPORTP (port))
  2587. scm_flush_unlocked (port);
  2588. }
  2589. SCM_DEFINE (scm_flush_all_ports, "flush-all-ports", 0, 0, 0,
  2590. (),
  2591. "Equivalent to calling @code{force-output} on\n"
  2592. "all open output ports. The return value is unspecified.")
  2593. #define FUNC_NAME s_scm_flush_all_ports
  2594. {
  2595. scm_c_port_for_each (&flush_output_port, NULL);
  2596. return SCM_UNSPECIFIED;
  2597. }
  2598. #undef FUNC_NAME
  2599. /* Void ports. */
  2600. scm_t_bits scm_tc16_void_port = 0;
  2601. static int fill_input_void_port (SCM port SCM_UNUSED)
  2602. {
  2603. return EOF;
  2604. }
  2605. static void
  2606. write_void_port (SCM port SCM_UNUSED,
  2607. const void *data SCM_UNUSED,
  2608. size_t size SCM_UNUSED)
  2609. {
  2610. }
  2611. static SCM
  2612. scm_i_void_port (long mode_bits)
  2613. {
  2614. SCM ret;
  2615. ret = scm_c_make_port (scm_tc16_void_port, mode_bits, 0);
  2616. scm_port_non_buffer (SCM_PTAB_ENTRY (ret));
  2617. return ret;
  2618. }
  2619. SCM
  2620. scm_void_port (char *mode_str)
  2621. {
  2622. return scm_i_void_port (scm_mode_bits (mode_str));
  2623. }
  2624. SCM_DEFINE (scm_sys_make_void_port, "%make-void-port", 1, 0, 0,
  2625. (SCM mode),
  2626. "Create and return a new void port. A void port acts like\n"
  2627. "@file{/dev/null}. The @var{mode} argument\n"
  2628. "specifies the input/output modes for this port: see the\n"
  2629. "documentation for @code{open-file} in @ref{File Ports}.")
  2630. #define FUNC_NAME s_scm_sys_make_void_port
  2631. {
  2632. return scm_i_void_port (scm_i_mode_bits (mode));
  2633. }
  2634. #undef FUNC_NAME
  2635. /* Initialization. */
  2636. void
  2637. scm_init_ports ()
  2638. {
  2639. /* lseek() symbols. */
  2640. scm_c_define ("SEEK_SET", scm_from_int (SEEK_SET));
  2641. scm_c_define ("SEEK_CUR", scm_from_int (SEEK_CUR));
  2642. scm_c_define ("SEEK_END", scm_from_int (SEEK_END));
  2643. scm_tc16_void_port = scm_make_port_type ("void", fill_input_void_port,
  2644. write_void_port);
  2645. cur_inport_fluid = scm_make_fluid ();
  2646. cur_outport_fluid = scm_make_fluid ();
  2647. cur_errport_fluid = scm_make_fluid ();
  2648. cur_loadport_fluid = scm_make_fluid ();
  2649. scm_i_port_weak_set = scm_c_make_weak_set (31);
  2650. #include "libguile/ports.x"
  2651. /* Use Latin-1 as the default port encoding. */
  2652. SCM_VARIABLE_SET (default_port_encoding_var,
  2653. scm_make_fluid_with_default (SCM_BOOL_F));
  2654. scm_port_encoding_init = 1;
  2655. SCM_VARIABLE_SET (default_conversion_strategy_var,
  2656. scm_make_fluid_with_default (sym_substitute));
  2657. scm_conversion_strategy_init = 1;
  2658. /* These bindings are used when boot-9 turns `current-input-port' et
  2659. al into parameters. They are then removed from the guile module. */
  2660. scm_c_define ("%current-input-port-fluid", cur_inport_fluid);
  2661. scm_c_define ("%current-output-port-fluid", cur_outport_fluid);
  2662. scm_c_define ("%current-error-port-fluid", cur_errport_fluid);
  2663. }
  2664. /*
  2665. Local Variables:
  2666. c-file-style: "gnu"
  2667. End:
  2668. */