forked from PolMine/RcppCWB
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcwb-encode.c
More file actions
1803 lines (1562 loc) · 74.3 KB
/
Copy pathcwb-encode.c
File metadata and controls
1803 lines (1562 loc) · 74.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* IMS Open Corpus Workbench (CWB)
* Copyright (C) 1993-2006 by IMS, University of Stuttgart
* Copyright (C) 2007- by the respective contributers (see file AUTHORS)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details (in the file "COPYING", or available via
* WWW at http://www.gnu.org/copyleft/gpl.html).
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
/* included by AB to ensure that winsock2.h is included before windows.h */
#ifdef __MINGW__
#include <winsock2.h> /* AB reversed order, in original CWB code windows.h is included first */
#endif
#include <ctype.h>
#include <math.h>
#include <stdarg.h>
#include <limits.h>
#include <time.h>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <glib.h>
#include "../cl/cl.h"
#include "../cl/cwb-globals.h"
#include "../cl/storage.h" /* for NwriteInt() & NwriteInts() */
#include "../cl/endian2.h"/* for byte order conversion functions */
void Rprintf(const char *, ...); /* alternative to include R_ext/Print.h */
#ifdef __MINGW__
#undef SUBDIR_SEPARATOR
#undef SUBDIR_SEP_STRING
#define SUBDIR_SEPARATOR '/'
#define SUBDIR_SEP_STRING "/"
#endif
/* ---------------------------------------------------------------------- */
/** User privileges of new files (octal format) */
#define UMASK 0644
/** String containing the characters that can function as field separators */
#define FIELDSEPS "\t\n"
/** Max number of attributes of a single kind (s or p). */
#define MAX_ATTRIBUTES 1024
/** nr of buckets of lexhashes used for checking duplicate errors (undeclared element and attribute names in XML tags) */
#define REP_CHECK_LEXHASH_SIZE 1000
/** Input buffer size. If we have XML tags with attributes, input lines can become pretty long
* (but there's basically just a single buffer)
*/
#define MAX_INPUT_LINE_LENGTH 65536
/** Normal extension for CWB input text files. (must have exactly 4 characters; .gz/.bz2 may be added to this if the file is compressed.) */
#define DEFAULT_INFILE_EXTENSION ".vrt"
/* implicit knowledge about CL component files naming conventions: format strings for printf and friends that combine a directory with an attribute name. */
#define PATH_STRUC_RNG "%s" SUBDIR_SEP_STRING "%s.rng" /**< Path implementing CL naming convention for S-attribute RNG files */
#define PATH_STRUC_AVX "%s" SUBDIR_SEP_STRING "%s.avx" /**< Path implementing CL naming convention for S-attribute AVX (att-val index) files */
#define PATH_STRUC_AVS "%s" SUBDIR_SEP_STRING "%s.avs" /**< Path implementing CL naming convention for S-attribute AVS (attribute values) files */
#define PATH_POS_CORPUS "%s" SUBDIR_SEP_STRING "%s.corpus" /**< Path implementing CL naming convention for P-attribute Corpus files */
#define PATH_POS_LEX "%s" SUBDIR_SEP_STRING "%s.lexicon" /**< Path implementing CL naming convention for P-attribute Lexicon files */
#define PATH_POS_LEXIDX "%s" SUBDIR_SEP_STRING "%s.lexicon.idx" /**< Path implementing CL naming convention for P-attribute Lexicon-index files */
/* ---------------------------------------------------------------------- */
/* global variables representing configuration */
extern char *field_separators; /**< string containing the characters that can function as field separators */
extern char *undef_value; /**< string used as value of P-attributes when a value is missing,
ie if a tab-delimited field is empty */
extern int debugmode; /**< debug mode on or off? */
extern int quietly; /**< hide messages */
extern int verbose; /**< show progress (this is _not_ the opposite of silent!) */
extern int xml_aware; /**< substitute XML entities in p-attributes & ignore <? and <! lines */
extern int skip_empty_lines; /**< skip empty lines when encoding? */
extern int auto_null; /**< auto-declare null attributes for unknown XML tags */
extern unsigned line; /**< corpus position currently being encoded (ie cpos of _next_ token);
unsigned so it doesn't wrap after first 2^31 tokens
and thus we can abort encoding when corpus size is exceeded */
extern int strip_blanks; /**< strip leading and trailing blanks from input and token annotations */
extern cl_string_list input_files; /**< list of input file(s) (-f option(s)) */
extern int nr_input_files; /**< number of input files (length of list after option processing) */
extern int current_input_file; /**< index of input file currently being processed */
extern char *current_input_file_name; /**< filename of current input file, for error messages */
extern FILE *input_fh; /**< file handle for current input file (or pipe) (text mode!) */
extern unsigned long input_line; /**< input line number (reset for each new file) for error messages */
extern char *registry_file; /**< if set, auto-generate registry file named {registry_file}, listing declared attributes */
extern char *directory; /**< corpus data directory (no longer defaults to current directory) */
extern const char *encoding_charset_name; /**< character set label that is inserted into the registry file */
extern CorpusCharset encoding_charset; /**< a charset object to be generated from corpus_character_set */
extern int clean_strings; /**< clean up input strings by replacing invalid bytes with '?' */
extern int numbered; /**< alternative input mode with token lines numbered in first column */
extern int encode_token_numbers; /**< whether token numbers in this input mode are encoded in a p-attribute */
extern char *conll_sentence_attribute; /**< encode blank lines as sentence breaks in this attribute */
/* ---------------------------------------------------------------------- */
/* cwb-encode encodes S-attributes and P-attributes, so there is an object-type and global array representing each. */
/**
* s_att_builder object: represents an S-attribute being encoded, and holds some
* information about the currently-being-processed instance of that S-attribute.
*/
typedef struct s_att_builder {
char *dir; /**< directory where this s-attribute is stored */
char *name; /**< name of the s-attribute */
int in_registry; /**< with "-R {reg_file}", this is set to 1 when the attribute is written to the registry
(avoid duplicates) */
int store_values; /**< flag indicating whether to store values (does _not_ automatically apply to children, see below) */
int feature_set; /**< stored values are feature sets => validate and normalise format */
int null_attribute; /**< a NULL attribute ignores all corresponding XML tags, without checking structure or annotations */
int automatic; /**< automatic attributes are the 'children' used for recursion and element attributes below */
FILE *rng_fh; /**< fh of rng component (cpos start/end pairs for the attribute's ranges) */
FILE *avx_fh; /**< fh of avx component (the attribute value index) */
FILE *avs_fh; /**< fh of avs component (the attribute values) */
int offset; /**< string offset for next string (in avs component) */
cl_lexhash lh; /**< lexicon hash for attribute values */
int has_children; /**< whether attribute values of XML elements are stored in s-attribute 'children' */
cl_lexhash el_attributes; /**< maps XML element attribute names to the appropriate s-attribute 'children' (s_att_builder *) */
cl_string_list el_atts_list; /**< list of declared element attribute names, required by s_att_close_range() function */
cl_lexhash el_undeclared_attributes; /**< remembers undeclared element attributes, so warnings will be issued only once */
int max_recursion; /**< maximum auto-recursion level; 0 = no recursion (maximal regions), -1 = assume flat structure */
int recursion_level; /**< keeps track of level of embedding when auto-recursion is activated */
int element_drop_count; /**< count how many recursive subelements were dropped because of the max_recursion limit */
struct s_att_builder **recursion_children; /**< (usually very short) list of s-attribute 'children' for auto-recursion;
use as array; recursion_children[0] points to self! */
int is_open; /**< boolean: whether there is an open structure region at the moment */
int start_pos; /**< if this->is_open, remember start position of current range */
char *annot; /**< and annotation (if there is one) */
int num; /**< number of current (if this->is_open) or next region */
} s_att_builder;
/** A global array for keeping track of S-attributes being encoded. */
s_att_builder s_encoder[MAX_ATTRIBUTES];
/** @see s_encoder */
extern int s_encoder_ix;
extern s_att_builder *conll_sentence_satt; /**< optional hidden s-attribute for encoding blank lines as sentence breaks (-L option) */
/**
* p_att_builder object: represents a P-attribute being encoded.
*/
typedef struct {
char *name; /**< CWB name of the attribute */
cl_lexhash lh; /**< String hash object containing the lexicon for the encoded P attrbute */
int position; /**< Byte index of the lexicon file in progress; contains total number of bytes
written so far (== the beginning of the -next- string that is written) */
int feature_set; /**< Boolean: is this a feature set attribute? => validate and normalise format */
FILE *lex_fh; /**< file handle of lexicon component */
FILE *lexidx_fh; /**< file handle of lexicon index component */
FILE *corpus_fh; /**< file handle of corpus component */
} p_att_builder;
/** A global array for keeping track of P-attributes being encoded. */
p_att_builder p_encoder[MAX_ATTRIBUTES];
/** @see p_encoder */
extern int p_encoder_ix;
/**
* lookup hash for undeclared s-attributes and s-attributes declared with -S that
* have annotations (which will be ignored), so warnings are issued only once
*/
extern cl_lexhash undeclared_sattrs;
/** name of the currently running program */
/* char *progname = NULL; */
/* ======================================== helper function */
/**
* A replacement for the strtok() function which doesn't skip empty fields.
*
* @param s The string to split.
* @param delim Delimiters to use in splitting.
* @return The next token from the string.
*/
char *
encode_strtok(char *s, const char *delim)
{
char *spanp;
int c, sc;
char *tok;
static char *last;
if (s == NULL && (s = last) == NULL)
return NULL;
c = *s++;
if (c == 0) /* no non-delimiter characters */
return last = NULL;
tok = s - 1;
while (1) {
spanp = (char *)delim;
do {
if ((sc = *spanp++) == c) {
if (c == 0)
s = NULL;
else
s[-1] = 0;
last = s;
return (tok);
}
} while (sc != 0);
c = *s++;
}
/* NOTREACHED */
return NULL;
}
/* ======================================== print time */
/**
* Prints a message plus the current time to the specified file/stream.
*
* @param stream Stream to print to.
* @param msg Message to incorporate into the string that is printed.
*/
void
encode_print_time(char *msg)
{
time_t now;
time(&now);
if (msg)
Rprintf("%s: %s\n", msg, ctime(&now));
else
Rprintf("Time: %s\n", ctime(&now));
}
/* ======================================== print error message and exit */
/**
* Prints the input line number (and input filename, if applicable) on STDERR,
* for error messages and warnings.
*/
void
encode_print_input_lineno(void)
{
if (nr_input_files > 0 && current_input_file_name != NULL)
Rprintf("file %s, line #%ld", current_input_file_name, input_line);
else
Rprintf("input line #%ld", input_line);
}
/**
* Prints an error message to STDERR, automatically adding a
* message on the location of the error in the corpus.
*
* Then exits the program.
*
* @param format Format-specifying string of the error message.
* @param ... Additional arguments, printf-style.
*/
int
encode_error(char *format, ...)
{
va_list ap;
va_start(ap, format);
if (format) {
Rprintf(format, ap);
Rprintf("\n");
}
else
Rprintf("Internal error. Aborted.\n");
if ((input_line > 0) || (current_input_file > 0)) {
/* show location only if we've already been reading input */
Rprintf("[location of error: ");
encode_print_input_lineno();
Rprintf("]\n");
}
return 1;
}
/* =================================================== processing directories of input files */
/**
* Get a list of files in a given directory.
*
* This function only lists files with .vrt or .vrt.(gz|bz2) extensions,
* and only files identified by POSIX stat() as "regular".
*
* (Note that .vrt is dependent on DEFAULT_INFILE_EXTENSION.)
*
* @see DEFAULT_INFILE_EXTENSION
* @param dir Path of directory to look in.
* @return List of paths to files (*including* the directory name).
* Returned as a cl_string_list object.
*/
cl_string_list
encode_scan_directory(char *dir)
{
DIR *dirp;
struct dirent *dp;
struct stat statbuf;
int n_files = 0;
int len_dir = strlen(dir);
cl_string_list input_files = cl_new_string_list();
dirp = opendir(dir);
if (dirp == NULL) {
perror("Can't access directory");
encode_error("Failed to scan directory specified with -F %s -- aborted.\n", dir);
}
errno = 0;
for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {
char *name = dp->d_name;
if (name != NULL) {
int len_name = strlen(name);
if ( (len_name >= 5 && (0 == strcasecmp(name + len_name - 4, DEFAULT_INFILE_EXTENSION)))
|| (len_name >= 8 && (0 == strcasecmp(name + len_name - 7, DEFAULT_INFILE_EXTENSION ".gz")))
|| (len_name >= 9 && (0 == strcasecmp(name + len_name - 8, DEFAULT_INFILE_EXTENSION ".bz2"))) )
{
char *full_name = (char *) cl_malloc(len_dir + len_name + 2);
sprintf(full_name, "%s%c%s", dir, SUBDIR_SEPARATOR, name);
if (stat(full_name, &statbuf) != 0) {
perror("Can't stat file:");
encode_error("Failed to access input file %s -- aborted.\n", full_name);
}
if (S_ISREG(statbuf.st_mode)) {
cl_string_list_append(input_files, full_name);
n_files++;
}
else
cl_free(full_name);
}
}
}
if (errno != 0) {
perror("Error reading directory");
encode_error("Failed to scan directory specified with -F %s -- aborted.\n", dir);
}
if (n_files == 0)
Rprintf("Warning: No input files found in directory -F %s !!\n", dir);
closedir(dirp);
cl_string_list_qsort(input_files);
return(input_files);
}
/* =================================================== handling s-attributes and p-attributes */
/**
* Gets the index (in the global s_encoder array) of the encoder of a specified S-attribute.
*
* @see s_encoder
* @param name The S-attribute to search for.
* @return Index (as integer). -1 if the S-attribute is not found.
*/
int
s_att_builder_find(char *name)
{
int i;
for (i = 0; i < s_encoder_ix; i++)
if (cl_streq(s_encoder[i].name, name))
return i;
return -1;
}
/**
* Prints registry lines for a given s-attribute, and its children,
* if any, to the specified file handle.
*
* @param encoder The s-attribute in question.
* @param dst Stream for the registry file to write the line to.
* @param print_comment Boolean: if true, a comment on the original XML tags is printed.
*/
void
s_att_print_registry_line(s_att_builder *encoder, FILE *dst, int print_comment)
{
s_att_builder *child;
int i, n_atts;
if (encoder->in_registry)
return;
else
encoder->in_registry = 1; /* make a note that we've already handled the range */
if (! encoder->null_attribute) {
if (print_comment) {
/* print comment showing corresponding XML tags */
fprintf(dst, "# <%s", encoder->name);
if (encoder->has_children) { /* if there are element attributes, show them in the order of declaration */
n_atts = cl_string_list_size(encoder->el_atts_list);
for (i = 0; i < n_atts; i++)
fprintf(dst, " %s=\"..\"", cl_string_list_get(encoder->el_atts_list, i));
}
fprintf(dst, "> ... </%s>\n", encoder->name);
/* print comment showing hierarchical structure (if not flat) */
if (encoder->max_recursion == 0)
fprintf(dst, "# (no recursive embedding allowed)\n");
else if (encoder->max_recursion > 0) {
n_atts = encoder->max_recursion;
fprintf(dst, "# (%d levels of embedding: <%s>", n_atts, encoder->name);
for (i = 1; i <= n_atts; i++)
fprintf(dst, ", <%s>", encoder->recursion_children[i]->name);
fprintf(dst, ").\n");
}
}
/* print registry line for this s-attribute */
fprintf(dst, encoder->store_values ? "STRUCTURE %-20s # [annotations]\n" : "STRUCTURE %s\n", encoder->name);
/* print recursion children, then element attribute children */
if (encoder->max_recursion > 0) {
n_atts = encoder->max_recursion;
for (i = 1; i <= n_atts; i++)
s_att_print_registry_line(encoder->recursion_children[i], dst, 0);
}
/* element attribute children will print their recursion children as well */
if (encoder->has_children) {
n_atts = cl_string_list_size(encoder->el_atts_list);
for (i = 0; i < n_atts; i++) {
cl_lexhash_entry entry = cl_lexhash_find(encoder->el_attributes, cl_string_list_get(encoder->el_atts_list, i));
child = (s_att_builder *) entry->data.pointer;
s_att_print_registry_line(child, dst, 0);
}
}
/* print blank line after each att. declaration block headed by comment */
if (print_comment)
fprintf(dst, "\n");
}
}
/**
* Creates a s_att_builder object to store a specified s-attribute
* (and, if appropriate, does the same for children-attributes).
*
* The new s_att_builder object is placed in a global variable, but a pointer
* is also returned. So you can ignore the return value or not, as
* you prefer.
*
* This is the function where the command-line formalism for defining
* s-attributes is defined.
*
* @see s_encoder
*
* @param name The string from the user specifying the name of
* this attribute, recursion and any "attributes"
* of this XML element - e.g. "text:0+id"
* @param directory The directory where the CWB data files will go.
* @param store_values boolean: indicates whether this s-attribute was
* specified with -V (true) or -S (false) when the
* program was invoked.
* @param null_attribute boolean: this is a null attribute, i.e. an XML
* element to be ignored.
* @return Pointer to the new s_att_builder object
* (which is a member of the global array).
*/
s_att_builder *
s_att_declare(char *name, char *directory, int store_values, int null_attribute)
{
char buf[CL_MAX_LINE_LENGTH];
s_att_builder *sbuilder;
char *p, *rec, *ea_start, *ea;
cl_lexhash_entry entry;
int i, is_feature_set;
char *flag_SV = (store_values) ? "-V" : "-S";
if (debugmode)
Rprintf("ATT: %s %s\n", flag_SV, name);
if (s_encoder_ix >= MAX_ATTRIBUTES)
encode_error("Too many s-attributes declared (last was <%s>).", name);
if (directory == NULL)
encode_error("Error: you must specify a directory for CWB data files with the -d option");
sbuilder = &s_encoder[s_encoder_ix]; /* fill next entry in s_encoder[] */
s_encoder_ix++; /* must increment range index now, in case we have children */
cl_strcpy(buf, name);
/* check if recursion and/or element attributes are declared */
if ((rec = strchr(buf, ':')) != NULL) { /* recursion declaration ":<n>" */
*(rec++) = '\0';
if (strchr(buf, '+')) /* make sure recursion is declared _before_ element attributes */
encode_error("Usage error: recursion depth must be declared before element attributes in %s %s !", flag_SV, name);
}
p = (rec != NULL) ? rec : buf; /* start looking for element attribute declarations from here */
if (NULL != (ea_start = strchr(p, '+')) ) /* element att. declaration "+<ea>" */
*(ea_start++) = '\0';
/* by default - not a feature set. Then test. */
is_feature_set = 0;
if (buf[strlen(buf)-1] == '/') {
is_feature_set = 1;
buf[strlen(buf)-1] = '\0';
if (!store_values)
encode_error("Usage error: feature set marker '/' is meaningless with -S flag in %s %s !", flag_SV, name);
if (ea_start != NULL)
encode_error("Usage error: values of s-attribute %s cannot be feature sets if element attributes are declared (%s %s).",
buf, flag_SV, name);
}
/* now buf points to <name> rec points to <n> and ea_start to <ea> of the first element att.;
all strings are NUL-terminated (ea_start has the form "<ea1>+<ea2>+...+<ea_n>" */
sbuilder->name = cl_strdup(buf); /* name of the s-attribute */
sbuilder->dir = cl_strdup(directory);
sbuilder->in_registry = 0;
sbuilder->store_values = store_values;
sbuilder->feature_set = is_feature_set;
sbuilder->max_recursion = (rec) ? atoi(rec) : -1; /* set recursion depth: -1 = flat structure */
sbuilder->recursion_level = 0;
sbuilder->automatic = 0;
sbuilder->null_attribute = 0;
if (null_attribute) {
sbuilder->null_attribute = 1;
if (rec != NULL || ea_start != NULL)
Rprintf("Warning: recursion and element attribute specifiers are ignored for null attributes (-0 %s).'n", name);
return sbuilder;
/* stop initialisation here; other functions shouldn't do anything with this att */
}
if (ea_start != NULL)
ea_start = cl_strdup(ea_start); /* now buf can be re-used for pathnames below */
/* open data files for this s-attribute (children will be added later) */
/* create .rng component */
sprintf(buf, PATH_STRUC_RNG, directory, sbuilder->name);
if ((sbuilder->rng_fh = fopen(buf, "wb")) == NULL) {
perror(buf);
encode_error("Can't write .rng file for s-attribute <%s>.", name);
}
if (sbuilder->store_values) {
/* create .avx and .avs components and initialise lexicon hash */
sprintf(buf, PATH_STRUC_AVS, sbuilder->dir, sbuilder->name);
if ((sbuilder->avs_fh = fopen(buf, "wb")) == NULL) {
perror(buf);
encode_error("Can't write .avs file for s-attribute <%s>.", name);
}
sprintf(buf, PATH_STRUC_AVX, sbuilder->dir, sbuilder->name);
if ((sbuilder->avx_fh = fopen(buf, "wb")) == NULL) {
perror(buf);
encode_error("Can't write .avx file for s-attribute <%s>.", name);
}
sbuilder->lh = cl_new_lexhash(10000); /* typically, will only have moderate number of entries -> save memory */
}
else {
sbuilder->avs_fh = NULL;
sbuilder->avx_fh = NULL;
sbuilder->lh = NULL;
}
sbuilder->offset = 0;
sbuilder->is_open = 0;
sbuilder->start_pos = 0;
sbuilder->annot = NULL;
sbuilder->num = 0;
/* now that the range is initialised, declare its 'children' if necessary */
if (sbuilder->max_recursion >= 0) {
sbuilder->recursion_children = (s_att_builder **) cl_calloc(sbuilder->max_recursion + 1, sizeof(s_att_builder *));
sbuilder->recursion_children[0] = sbuilder; /* zeroeth recursion level is stored in the att. itself */
for (i = 1; i <= sbuilder->max_recursion; i++) {
/* recursion children have 'flat' structure, because recursion is handled explicitly */
sprintf(buf, "%s%d%s", sbuilder->name, i, is_feature_set ? "/" : "");
sbuilder->recursion_children[i] = s_att_declare(buf, sbuilder->dir, sbuilder->store_values, /*null*/ 0);
sbuilder->recursion_children[i]->automatic = 1; /* mark as automatically handled attribute */
}
sbuilder->recursion_level = 0;
sbuilder->element_drop_count = 0;
}
/* element attributes children can handle recursion on their own */
if (ea_start == NULL) {
sbuilder->has_children = 0;
}
else {
s_att_builder *att_ptr;
sbuilder->has_children = 1;
sbuilder->el_attributes = cl_new_lexhash(REP_CHECK_LEXHASH_SIZE);
sbuilder->el_atts_list = cl_new_string_list();
sbuilder->el_undeclared_attributes = cl_new_lexhash(REP_CHECK_LEXHASH_SIZE);
ea = ea_start;
while (ea != NULL) {
if ((p = strchr(ea, '+')) != NULL)
*p = '\0'; /* ea now points to NUL-terminated "<ea_i>" */
if (sbuilder->max_recursion >= 0)
sprintf(buf, "%s_%s:%d", sbuilder->name, ea, sbuilder->max_recursion);
else
sprintf(buf, "%s_%s", sbuilder->name, ea);
/* potential feature set marker (/) is passed on to the respective child attribute and handled there */
if (ea[strlen(ea)-1] == '/')
ea[strlen(ea)-1] = '\0'; /* remove feature set marker from element attribute name (used for lookup in encoding) */
if (cl_lexhash_id(sbuilder->el_attributes, ea) >= 0)
encode_error("Element attribute <%s %s=...> declared twice!", sbuilder->name, ea);
entry = cl_lexhash_add(sbuilder->el_attributes, ea);
att_ptr = s_att_declare(buf, sbuilder->dir, 1, /*null*/ 0); /* element att. children always store value, of course */
att_ptr->automatic = 1; /* mark as automatically handled attribute */
entry->data.pointer = att_ptr;
cl_string_list_append(sbuilder->el_atts_list, cl_strdup(ea)); /* make copy of name (for code cleanness) */
if (p != NULL)
ea = p + 1 ;
else
ea = NULL; /* end of element att declarations */
}
cl_free(ea_start); /* don't forget to free copy of element att declaration */
}
return sbuilder;
}
/**
* Closes a currently open instance (aka region, range) of an S-attribute.
*
* @param encoder Pointer to the S-attribute builder whose range should close.
* @param end_pos The corpus position at which this instance closes.
*/
void
s_att_close_range(s_att_builder *encoder, int end_pos)
{
cl_lexhash_entry entry;
int close_this_range = 0; /* whether we actually have to close this range (may be skipped or delegated in recursion mode) */
int i, n_children, annot_len;
if (debugmode)
Rprintf("Close range of <%s> at cpos %d, line %ld\n", encoder->name, end_pos, input_line);
if (encoder->null_attribute) /* do nothing for NULL attributes */
return;
if (encoder->max_recursion >= 0) { /* recursive XML structure */
encoder->recursion_level--; /* decrement level of nesting */
if (encoder->recursion_level < 0) {
/* extra close tag (ignored) */
encoder->recursion_level = 0;
if (!quietly) {
Rprintf("Close tag </%s> without matching open tag ignored (", encoder->name);
encode_print_input_lineno();
Rprintf(").\n");
}
}
else if (encoder->recursion_level > encoder->max_recursion) {
/* deeply nested ranges are ignored silently and only listed at the end (cf. s_att_open_range() below) */
/*
if (!quietly) {
Rprintf("Close tag </%s> too deeply nested, ignored (", encoder->name);
encode_print_input_lineno();
Rprintf(").\n");
}
*/
}
else if (encoder->recursion_level > 0)
/* delegated to appropriate recursion child */
s_att_close_range(encoder->recursion_children[encoder->recursion_level], end_pos);
else
/* encoder->recursion_level == 0, i.e. the close tag actually applies to the present s-attribute (and not a ...1, ...2 suffix etc.) */
close_this_range = 1;
}
else { /* flat structure (traditional mode) */
if (encoder->is_open)
close_this_range = 1; /* ok */
else {
/* extra close tag (ignored) */
if (!quietly) {
Rprintf("Close tag </%s> without matching open tag ignored (", encoder->name);
encode_print_input_lineno();
Rprintf(").\n");
}
}
}
/* now close the range and write data to disk if we really have to */
if (close_this_range) {
if (end_pos >= encoder->start_pos) {
/* write (start, end) to .rng component */
NwriteInt(encoder->start_pos, encoder->rng_fh);
NwriteInt(end_pos, encoder->rng_fh);
if (encoder->store_values) {
/* shouldn't happen, but just to be on the safe side ... */
if (encoder->annot == NULL)
encoder->annot = cl_strdup("");
/* check annotation length & truncate if necessary */
annot_len = strlen(encoder->annot);
if (annot_len >= CL_MAX_LINE_LENGTH) {
char *target;
if (!quietly) {
Rprintf("Value of <%s> region exceeds maximum string length (%d > %d chars), truncated (", encoder->name, annot_len, CL_MAX_LINE_LENGTH-1);
encode_print_input_lineno();
Rprintf(").\n");
}
encoder->annot[CL_MAX_LINE_LENGTH-2] = '$'; /* truncation marker, as e.g. in Emacs */
encoder->annot[CL_MAX_LINE_LENGTH-1] = '\0';
/* truncation may break UTF-8 strings */
if (utf8 == encoding_charset && !g_utf8_validate((const gchar *)encoder->annot, -1, (const gchar **)&target))
*target = '$', *(target+1) = '\0';
}
/* check if annot is already in hash */
if (!(entry = cl_lexhash_find(encoder->lh, encoder->annot))) {
/*
* present annotation was not found in the hash - so it is a new value.
* so insert annotation string into lexicon hash (with the avs offset as data.integer)
*/
entry = cl_lexhash_add(encoder->lh, encoder->annot);
entry->data.integer = encoder->offset;
/* write annotation string to .avs component (at offset encoder->offset) */
fprintf(encoder->avs_fh, "%s%c", encoder->annot, '\0');
/* update offset, ready for the next annotation string; next str begins at (string length + null byte) */
encoder->offset += annot_len + 1;
/* just in case: check for integer overflow */
if (encoder->offset < 0)
encode_error("Too many annotation values for <%s> regions (lexicon size > %d bytes)", encoder->name, INT_MAX);
}
/* so at this point, either way, the annotation is in the hash (and hence, on disk in the .avs component)
and we have its avs-offset in the *entry* variable's integer member. */
/* write (range_number, offset) to .avx component */
NwriteInt(encoder->num, encoder->avx_fh); /* this was intended for 'sparse' annotations, which I don't like (so they're no longer there) */
NwriteInt(entry->data.integer, encoder->avx_fh);
/* throw away the now-written annotation, and incremement the number, ready for the next range. */
encoder->num++;
cl_free(encoder->annot);
}
/* endif store_values */
encoder->is_open = 0;
} /* endif end_pos >= start_pos */
else {
encoder->is_open = 0; /* silently ignore empty region */
cl_free(encoder->annot);
}
}
/* if this att has element attribute children, send corresponding close_range() event to all children in the list
(recursion and nesting errors will be handled by the children themselves) */
if (encoder->has_children) {
n_children = cl_string_list_size(encoder->el_atts_list);
for (i = 0; i < n_children; i++) {
entry = cl_lexhash_find(encoder->el_attributes, cl_string_list_get(encoder->el_atts_list, i));
if (entry == NULL)
encode_error("Internal error in <%s>: encoder->el_attributes inconsistent with encoder->el_atts_list!", encoder->name);
s_att_close_range((s_att_builder *) entry->data.pointer, end_pos);
}
}
}
/**
* Opens an instance of the given S-attribute.
*
* If encoder has element attribute children, range_open() will mess around
* with the string annotation (otherwise not).
*
* @param encoder The S-attribute to open.
* @param start_pos The corpus position at which this instance begins.
* @param annot The annotation string (the XML element's att-val pairs).
*/
void
s_att_open_range(s_att_builder *encoder, int start_pos, char *annot)
{
cl_lexhash_entry entry;
int open_this_range = 0; /* whether we actually have to open this range (may be skipped or delegated in recursion mode) */
int i, mark, point, n_children;
char *el_att_name, *el_att_value;
char quote_char; /* quote char used for element attribute value ('"' or '\'') */
if (debugmode)
Rprintf("Open range of <%s> at cpos %d, line %ld\n", encoder->name, start_pos, input_line);
if (encoder->null_attribute) /* do nothing for NULL attributes */
return;
if (encoder->max_recursion >= 0) {
/* recursive XML structure */
if (encoder->recursion_level > encoder->max_recursion)
/* deeply nested ranges are ignored; count how many we've lost */
/* NB: an option to raise a warning here could be useful to make it easier to locate such format errors in input files */
encoder->element_drop_count++;
else if (encoder->recursion_level > 0)
/* delegate to appropriate recursion child (with same annotation) */
s_att_open_range(encoder->recursion_children[encoder->recursion_level], start_pos, (encoder->store_values) ? annot : NULL);
/* recursion children don't parse the annotation string, so annot will remain untouched;
since recursion children always have the same -S or -V behaviour as the parent, we only
pass the annotation string for -V attributes in order to avoid spurious warnings */
else /* encoder->recursion_level == 0, i.e. the "open" actually applies to the present s-attribute */
open_this_range = 1;
encoder->recursion_level++; /* increment level of nesting */
}
else {
/* flat structure (traditional mode) */
if (encoder->is_open)
/* if we assume flat structure, implicitly close a range that is already open */
s_att_close_range(encoder, start_pos - 1);
open_this_range = 1; /* with flat structure, a start tag always opens a new range */
}
if (open_this_range) {
encoder->is_open = 1;
encoder->start_pos = line;
if (annot == NULL) /* shouldn't happen, but just to be on the safe side ... */
annot = "";
if (encoder->store_values) {
encoder->annot = cl_strdup(annot); /* remember annotation for s_att_close_range(); must strdup because it's pointer into linebuf[] */
/* don't warn about empty annotations, because that's explicitly allowed! */
if (strip_blanks) { /* annotation string may have trailing blanks */
i = strlen(encoder->annot) - 1;
while (i >= 0 && (encoder->annot[i] == ' ' || encoder->annot[i] == '\t'))
encoder->annot[i--] = '\0';
}
if (encoder->feature_set) {
char *token = cl_make_set(encoder->annot, /*split*/ 0);
if (token == NULL) {
if (! quietly) {
Rprintf("Warning: '%s' is not a valid feature set for s-attribute %s, replaced by empty set | (",
encoder->annot, encoder->name);
encode_print_input_lineno();
Rprintf(")\n");
}
token = cl_strdup("|"); /* encoder->annot will be free()d later, so it must be an allocated string */
}
cl_free(encoder->annot);
encoder->annot = token;
}
}
else {
/* warn about non-empty annotation string in -S attribute (unless annotation string is parsed), but only once */
if ((!encoder->has_children) && (*annot != '\0')) {
if (!cl_lexhash_freq(undeclared_sattrs, encoder->name)) {
if (!quietly) {
Rprintf("Annotations of s-attribute <%s> not stored (", encoder->name);
encode_print_input_lineno();
Rprintf(", warning issued only once).\n");
}
cl_lexhash_add(undeclared_sattrs, encoder->name); /* we can re-use the lookup hash for undeclared s-attributes :o) */
}
}
}
}
/* if encoder has element attribute children, try to parse the annotation string into
XML attribute="value" or attribute=id pairs (destructively modifying the original)
NB: there must not be any leading whitespace in annot
NB: we don't bother about recursion here; the child attributes will take care of that themselves */
if (encoder->has_children) {
/* we have to make sure that regions are opened for all declared element attributes, and that
no element attribute occurs more than once in order to ensure proper nesting; */
n_children = cl_string_list_size(encoder->el_atts_list); /* use the integer data field of the el_attributes hash */
for (i = 0; i < n_children; i++) {
entry = cl_lexhash_find(encoder->el_attributes, cl_string_list_get(encoder->el_atts_list, i));
entry->data.integer = 0; /* initialise to 0, i.e. "not handled" */
}
mark = 0; /* mark and point are offsets into annot[] */
while (annot[mark] != '\0') {
point = mark;
/* identify XML element attribute name (slightly relaxed attribute naming conventions) */
while (cl_xml_is_name_char(annot[point]))
point++;
while ((annot[point] == ' ') || (annot[point] == '\t')) {
annot[point] = '\0'; /* skip optional whitespace before '=' separator, and remove it from el.att. name */
point++;
}
/* now annot[point] should be the separator '=' char */
if (annot[point] != '=') {
if (!quietly) {
Rprintf("Attributes of open tag <%s ...> ignored because of syntax error (``='' not found) (", encoder->name);
encode_print_input_lineno();
Rprintf(").\n");
}
break; /* stop processing attributes */
}
annot[point] = '\0'; /* terminate el. attribute name in el_att_name = (annot+mark) */
el_att_name = annot + mark;
mark = point + 1;
while ((annot[mark] == ' ') || (annot[mark] == '\t'))
mark++; /* skip optional whitespace after '=' separator */
/* now get the attribute value (either "value" or 'value' or id) */
quote_char = annot[mark];
if ((quote_char == '"') || (quote_char == '\'')) { /* attribute="value" or attribute='value' format */
mark++; /* assume it's well-formed XML and just look for next occurrence of quote_char */
point = mark;
while ((annot[point] != quote_char) && (annot[point] != '\0'))
point++;
if (annot[point] == '\0') { /* syntax error: missing end quote */
if (!quietly) {
Rprintf("Attributes of open tag <%s ...> ignored because of syntax error (value missing end quote) (", encoder->name);
encode_print_input_lineno();
Rprintf(").\n");
}
break; /* stop processing attributes */
}
el_att_value = annot + mark;
annot[point] = '\0'; /* terminate attribute value, and advance mark */
mark = point + 1;
}
else { /* attribute=id format (accepts same id's as el.att. name) */
point = mark;
while (cl_xml_is_name_char(annot[point]))
point++;
el_att_value = annot + mark;
if (annot[point] == '\0') { /* end of annot[] reached, don't advance mark beyond NUL byte */
mark = point;
}
else { /* terminate attribute value, and advance mark */
annot[point] = '\0';
mark = point + 1;
}
if (strlen(el_att_value) == 0) { /* syntax error: attribute=id with empty value (not allowed) */
if (!quietly) {
Rprintf("Attributes of open tag <%s ...> ignored because of syntax error (attribute=id with empty value (not allowed)) (", encoder->name);
encode_print_input_lineno();
Rprintf(").\n");
}
break; /* stop processing attributes */
}
}
/* syntax check: el_att_name must be non-empty (values "" and '' are allowed) */
if (strlen(el_att_name) == 0) {
if (!quietly) {
Rprintf("Attributes of open tag <%s ...> ignored because of syntax error (empty attribute name)) (", encoder->name);
encode_print_input_lineno();
Rprintf(").\n");
}
break; /* stop processing attributes */
}