Codebase list ohcount / 8e3aae6
New upstream version 3.1.0 Sylvestre Ledru 6 years ago
262 changed file(s) with 10810 addition(s) and 3655 deletion(s). Raw diff Collapse all Expand all
1212 ruby/ohcount.so
1313 ruby/ohcount_wrap.c
1414 test/unit/run_tests.dSYM/
15 build-python/
16 python/ohcount.py
17 .rvmrc
18 .ruby-version
+0
-1
.pc/.quilt_patches less more
0 debian/patches
+0
-1
.pc/.quilt_series less more
0 series
+0
-1
.pc/.version less more
0 2
+0
-5
.pc/applied-patches less more
0 fix_null_dereference_2.patch
1 fix_null_dereference.patch
2 txx_support.patch
3 disabled_test_suite.patch
4 rbconfig.patch
+0
-162
.pc/disabled_test_suite.patch/build less more
0 #!/usr/bin/env bash
1 # Build script for Ohcount.
2 # Written by Mitchell Foral. mitchell<att>caladbolg.net.
3
4 # Options
5 # Change these for your system configuration.
6 if [ `uname` != "Darwin" ]
7 then
8 # Linux
9 INC_DIR=
10 LIB_DIR=
11
12 if [ `uname` == "FreeBSD" ]
13 then
14 INC_DIR=/usr/local/include
15 LIB_DIR=/usr/local/lib
16 fi
17
18 # You shouldn't have to change the following.
19 CFLAGS=-O3
20 CFLAGS="$CFLAGS -DTMP_FILES_ARE_DT_UNKNOWN" # workaround bug on centos/SF servers
21 WARN="-Wall -Wno-pointer-to-int-cast -Wno-parentheses"
22 SHARED=-shared
23 SHARED_NAME=libohcount.so
24 RB_SHARED=-shared
25 RB_SHARED_NAME=ohcount.so
26 else
27 # Mac OSX
28 INC_DIR=/opt/local/include
29 LIB_DIR=/opt/local/lib
30 # You shouldn't have to change the following.
31 CFLAGS="-fno-common -g"
32 WARN="-Wall -Wno-parentheses"
33 SHARED="-dynamiclib -L$LIB_DIR -lpcre"
34 SHARED_NAME=libohcount.dylib
35 RB_SHARED="-dynamic -bundle -lruby"
36 RB_SHARED_NAME=ohcount.bundle
37 fi
38
39 # C compiler and flags
40 cc="gcc -fPIC -g $CFLAGS $WARN -I$INC_DIR -L$LIB_DIR"
41
42 # Ohcount source files
43 files="src/sourcefile.c \
44 src/detector.c \
45 src/licenses.c \
46 src/parser.o \
47 src/loc.c \
48 src/log.c \
49 src/diff.c \
50 src/parsed_language.c \
51 src/hash/language_hash.c"
52
53 # If any src/hash/*.gperf file is newer than the header files (which were
54 # presumably generated together), regenerate the headers.
55 build_hash_headers()
56 {
57 if [[ -z `ls src/hash/ | grep "_hash.h$"` ||
58 ! -z `find src/hash/*.gperf -newer src/hash/parser_hash.h` ]]
59 then
60 echo "Generating hash headers"
61 sh -c "cd src/hash/ && ./generate_headers" || exit 1
62 fi
63 }
64
65 # If src/parser.o does not exist, or if there are Ragel parsers or parser
66 # header files newer than the existing parser.o, recompile parser.o.
67 build_parser_o()
68 {
69 if [[ ! -f src/parser.o ||
70 ! -z `find src/parsers/*.{h,rl} -newer src/parser.o` ]]
71 then
72 bash -c "cd src/parsers/ && bash ./compile" || exit 1
73 echo "Building src/parser.c (will take a while)"
74 bash -c "$cc -c src/parser.c -o src/parser.o" || exit 1
75 fi
76 }
77
78 build_shared()
79 {
80 build_hash_headers
81 build_parser_o
82 if [[ ! -f src/$SHARED_NAME ||
83 ! -z `find src/*.{h,c} -newer src/$SHARED_NAME` ]]
84 then
85 echo "Building shared library"
86 sh -c "$cc $SHARED $files -o src/$SHARED_NAME" || exit 1
87 fi
88 }
89
90 build_ohcount()
91 {
92 build_hash_headers
93 build_parser_o
94 echo "Building Ohcount"
95 mkdir -p bin/
96 sh -c "$cc src/ohcount.c $files -o bin/ohcount -lpcre" || exit 1
97 }
98
99 build_test_suite()
100 {
101 build_hash_headers
102 build_parser_o
103 echo "Building test suite"
104 sh -c "$cc test/unit/all_tests.c $files -o test/unit/run_tests -lpcre" \
105 || exit 1
106 }
107
108 run_test_suite()
109 {
110 echo "Running test suite"
111 sh -c "cd test/unit/ && ./run_tests"
112 }
113
114 build_ruby_bindings()
115 {
116 arch=`ruby -rmkmf -e 'print Config::expand(CONFIG["arch"])'`
117 echo "Generating Ruby bindings for $arch"
118 sh -c "swig -ruby -o ruby/ohcount_wrap.c ruby/ohcount.i" || exit 1
119 mkdir -p ruby/$arch
120 sh -c "$cc $RB_SHARED ruby/ohcount_wrap.c $files -o ruby/$arch/$RB_SHARED_NAME \
121 -I`ruby -rmkmf -e 'print Config::expand(CONFIG["archdir"])'` \
122 -lpcre" || exit 1
123 sh -c "cd test/unit/ruby && ruby ruby_test.rb" || exit 1
124 }
125
126 if [ $# -eq 0 ] || [ $1 == "all" ]
127 then
128 build_ohcount
129 build_test_suite
130 run_test_suite
131 echo $success
132 elif [ $1 == "shared" ]
133 then
134 build_shared
135 echo "Build successful; $SHARED_NAME is in src/"
136 elif [ $1 == "ohcount" ]
137 then
138 build_ohcount
139 echo "Build successful; ohcount is in bin/"
140 elif [ $1 == "tests" ]
141 then
142 build_test_suite
143 run_test_suite
144 elif [ $1 == "ruby" ]
145 then
146 build_ruby_bindings
147 echo "Build successful; $RB_SHARED_NAME is in ruby/$arch"
148 elif [ $1 == "clean" ]
149 then
150 rm -f bin/ohcount
151 rm -f test/unit/run_tests
152 rm -f src/parser.o
153 rm -f src/parsers/*.h
154 rm -f src/hash/*.h
155 rm -f src/hash/*.c
156 rm -f src/$SHARED_NAME
157 rm -f ruby/$RB_SHARED_NAME
158 rm -rf ruby/`ruby -rmkmf -e 'print Config::expand(CONFIG["arch"])'`/*
159 else
160 echo "Usage: build [all|ohcount|shared|tests|ruby|clean]"
161 fi
+0
-693
.pc/fix_null_dereference.patch/src/detector.c less more
0 // detector.c written by Mitchell Foral. mitchell<att>caladbolg.net.
1 // See COPYING for license information.
2
3 #include <ctype.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8
9 #include "detector.h"
10 #include "languages.h"
11 #include "log.h"
12
13 #include "hash/cppheader_hash.h"
14 #include "hash/disambiguatefunc_hash.h"
15 #include "hash/extension_hash.h"
16 #include "hash/filename_hash.h"
17
18 #define ISBINARY(x) (x[0] == '\1')
19 #define ISAMBIGUOUS(x) (x[0] == '\2')
20 #define DISAMBIGUATEWHAT(x) &x[1]
21
22 const char *ohcount_detect_language(SourceFile *sourcefile) {
23 const char *language = NULL;
24 char *p, *pe;
25 int length;
26
27 // Attempt to detect based on file extension.
28 length = strlen(sourcefile->ext);
29 struct ExtensionMap *re = ohcount_hash_language_from_ext(sourcefile->ext,
30 length);
31 if (re) language = re->value;
32 if (language == NULL) {
33 // Try the lower-case version of this extension.
34 char lowerext[length + 1];
35 strncpy(lowerext, sourcefile->ext, length);
36 lowerext[length] = '\0';
37 for (p = lowerext; p < lowerext + length; p++) *p = tolower(*p);
38 struct ExtensionMap *re = ohcount_hash_language_from_ext(lowerext, length);
39 if (re) return re->value;
40 }
41 if (language) {
42 if (ISAMBIGUOUS(language)) {
43 // Call the appropriate function for disambiguation.
44 length = strlen(DISAMBIGUATEWHAT(language));
45 struct DisambiguateFuncsMap *rd =
46 ohcount_hash_disambiguate_func_from_id(DISAMBIGUATEWHAT(language),
47 length);
48 if (rd) return rd->value(sourcefile);
49 } else return ISBINARY(language) ? NULL : language;
50 }
51
52 // Attempt to detect based on filename.
53 length = strlen(sourcefile->filename);
54 struct FilenameMap *rf =
55 ohcount_hash_language_from_filename(sourcefile->filename, length);
56 if (rf) return rf->value;
57
58 char line[81] = { '\0' }, buf[81];
59
60 // Attempt to detect using Emacs mode line (/^-\*-\s*mode[\s:]*\w/i).
61 p = ohcount_sourcefile_get_contents(sourcefile);
62 pe = p;
63 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
64 while (pe < eof) {
65 // Get the contents of the first line.
66 while (pe < eof && *pe != '\r' && *pe != '\n') pe++;
67 length = (pe - p <= sizeof(line)) ? pe - p : sizeof(line);
68 strncpy(line, p, length);
69 line[length] = '\0';
70 if (*line == '#' && *(line + 1) == '!') {
71 // First line was sh-bang; loop to get contents of second line.
72 while (*pe == '\r' || *pe == '\n') pe++;
73 p = pe;
74 } else break;
75 }
76 char *eol = line + strlen(line);
77 for (p = line; p < eol; p++) *p = tolower(*p);
78 p = strstr(line, "-*-");
79 if (p) {
80 p += 3;
81 while (*p == ' ' || *p == '\t') p++;
82 if (strncmp(p, "mode", 4) == 0) {
83 p += 4;
84 while (*p == ' ' || *p == '\t' || *p == ':') p++;
85 }
86 pe = p;
87 while (isalnum(*pe)) pe++;
88 length = pe - p;
89 strncpy(buf, p, length);
90 buf[length] = '\0';
91 struct LanguageMap *rl = ohcount_hash_language_from_name(buf, length);
92 if (rl) return rl->name;
93 }
94
95 // Attempt to detect based on Unix 'file' command.
96 int tmpfile = 0;
97 char *path = sourcefile->filepath;
98 if (sourcefile->diskpath)
99 path = sourcefile->diskpath;
100 if (access(path, F_OK) != 0) { // create temporary file
101 path = malloc(21);
102 strncpy(path, "/tmp/ohcount_XXXXXXX", 20);
103 *(path + 21) = '\0';
104 int fd = mkstemp(path);
105 char *contents = ohcount_sourcefile_get_contents(sourcefile);
106 log_it("contents:");
107 log_it(contents);
108 length = contents ? strlen(contents) : 0;
109 write(fd, contents, length);
110 close(fd);
111 tmpfile = 1;
112 }
113 char command[strlen(path) + 11];
114 sprintf(command, "file -b '%s'", path);
115 FILE *f = popen(command, "r");
116 if (f) {
117 fgets(line, sizeof(line), f);
118 char *eol = line + strlen(line);
119 for (p = line; p < eol; p++) *p = tolower(*p);
120 p = strstr(line, "script text");
121 if (p && p == line) { // /^script text(?: executable)? for \w/
122 p = strstr(line, "for ");
123 if (p) {
124 p += 4;
125 pe = p;
126 while (isalnum(*pe)) pe++;
127 length = pe - p;
128 strncpy(buf, p, length);
129 buf[length] = '\0';
130 struct LanguageMap *rl = ohcount_hash_language_from_name(buf, length);
131 if (rl) language = rl->name;
132 }
133 } else if (p) { // /(\w+)(?: -\w+)* script text/
134 do {
135 p--;
136 pe = p;
137 while (*p == ' ') p--;
138 while (p != line && isalnum(*(p - 1))) p--;
139 if (p != line && *(p - 1) == '-') p--;
140 } while (*p == '-'); // Skip over any switches.
141 length = pe - p;
142 strncpy(buf, p, length);
143 buf[length] = '\0';
144 struct LanguageMap *rl = ohcount_hash_language_from_name(buf, length);
145 if (rl) language = rl->name;
146 } else if (strstr(line, "xml")) language = LANG_XML;
147 pclose(f);
148 if (tmpfile) {
149 remove(path);
150 free(path);
151 }
152 if (language) return language;
153 }
154
155 return NULL;
156 }
157
158 const char *disambiguate_aspx(SourceFile *sourcefile) {
159 char *p = ohcount_sourcefile_get_contents(sourcefile);
160 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
161 for (; p < eof; p++) {
162 // /<%@\s*Page[^>]+Language="VB"[^>]+%>/
163 p = strstr(p, "<%@");
164 if (!p)
165 break;
166 char *pe = strstr(p, "%>");
167 if (p && pe) {
168 p += 3;
169 const int length = pe - p;
170 char buf[length];
171 strncpy(buf, p, length);
172 buf[length] = '\0';
173 char *eol = buf + strlen(buf);
174 for (p = buf; p < eol; p++) *p = tolower(*p);
175 p = buf;
176 while (*p == ' ' || *p == '\t') p++;
177 if (strncmp(p, "page", 4) == 0) {
178 p += 4;
179 if (strstr(p, "language=\"vb\""))
180 return LANG_VB_ASPX;
181 }
182 }
183 }
184 return LANG_CS_ASPX;
185 }
186
187 const char *disambiguate_b(SourceFile *sourcefile) {
188 char *p = ohcount_sourcefile_get_contents(sourcefile);
189 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
190 while (p < eof) {
191 // /(implement[ \t])|(include[ \t]+"[^"]*";)|
192 // ((return|break|continue).*;|(pick|case).*\{)/
193 if (strncmp(p, "implement", 9) == 0 &&
194 (*(p + 9) == ' ' || *(p + 9) == '\t'))
195 return LANG_LIMBO;
196 else if (strncmp(p, "include", 7) == 0 &&
197 (*(p + 7) == ' ' || *(p + 7) == '\t')) {
198 p += 7;
199 while (*p == ' ' || *p == '\t') p++;
200 if (*p == '"') {
201 while (*p != '"' && p < eof) p++;
202 if (*p == '"' && *(p + 1) == ';')
203 return LANG_LIMBO;
204 }
205 } else if (strncmp(p, "return", 6) == 0 ||
206 strncmp(p, "break", 5) == 0 ||
207 strncmp(p, "continue", 8) == 0) {
208 if (strstr(p, ";"))
209 return LANG_LIMBO;
210 } else if (strncmp(p, "pick", 4) == 0 ||
211 strncmp(p, "case", 4) == 0) {
212 if (strstr(p, "{"))
213 return LANG_LIMBO;
214 }
215 p++;
216 }
217 return disambiguate_basic(sourcefile);
218 }
219
220 const char *disambiguate_basic(SourceFile *sourcefile) {
221 char *p, *pe;
222 int length;
223
224 // Attempt to detect based on file contents.
225 char line[81];
226 p = ohcount_sourcefile_get_contents(sourcefile);
227 pe = p;
228 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
229 while (pe < eof) {
230 // Get a line at a time.
231 while (pe < eof && *pe != '\r' && *pe != '\n') pe++;
232 length = (pe - p <= sizeof(line)) ? pe - p : sizeof(line);
233 strncpy(line, p, length);
234 line[length] = '\0';
235 char *line_end = pe;
236
237 p = line;
238 if (isdigit(*p)) {
239 // /^\d+\s+\w/
240 p++;
241 while (isdigit(*p)) p++;
242 if (*p == ' ' || *p == '\t') {
243 p++;
244 while (*p == ' ' || *p == '\t') p++;
245 if (isalnum(*p))
246 return LANG_CLASSIC_BASIC;
247 }
248 }
249
250 // Next line.
251 pe = line_end;
252 while (*pe == '\r' || *pe == '\n') pe++;
253 p = pe;
254 }
255
256 // Attempt to detect from associated VB files in file context.
257 char **filenames = ohcount_sourcefile_get_filenames(sourcefile);
258 if (filenames) {
259 int i;
260 for (i = 0; filenames[i] != NULL; i++) {
261 pe = filenames[i] + strlen(filenames[i]);
262 p = pe;
263 while (p > filenames[i] && *(p - 1) != '.') p--;
264 length = pe - p;
265 if (length == 3 &&
266 (strncmp(p, "frm", length) == 0 ||
267 strncmp(p, "frx", length) == 0 ||
268 strncmp(p, "vba", length) == 0 ||
269 strncmp(p, "vbp", length) == 0 ||
270 strncmp(p, "vbs", length) == 0)) {
271 return LANG_VISUALBASIC;
272 }
273 }
274 }
275
276 return LANG_STRUCTURED_BASIC;
277 }
278
279 const char *disambiguate_cs(SourceFile *sourcefile) {
280 // Attempt to detect based on file contents.
281 char *contents = ohcount_sourcefile_get_contents(sourcefile);
282 if (contents && strstr(contents, "<?cs"))
283 return LANG_CLEARSILVER_TEMPLATE;
284 else
285 return LANG_CSHARP;
286 }
287
288 const char *disambiguate_fortran(SourceFile *sourcefile) {
289 char *p, *pe;
290
291 p = ohcount_sourcefile_get_contents(sourcefile);
292 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
293 while (p < eof) {
294 if (*p == ' ' && p + 5 < eof) {
295 int i;
296 for (i = 1; i <= 5; i++)
297 if (!isdigit(*(p + i)) && *(p + i) != ' ')
298 return LANG_FORTRANFIXED; // definately not f77
299 // Possibly fixed (doesn't match /^\s*\d+\s*$/).
300 pe = p;
301 while (*pe == ' ' || *pe == '\t') pe++;
302 if (pe - p <= 5) {
303 if (!isdigit(*pe))
304 return LANG_FORTRANFIXED;
305 while (isdigit(*pe)) pe++;
306 while (*pe == ' ' || *pe == '\t') pe++;
307 if (*pe != '\r' && *pe != '\n' && pe - p == 5)
308 return LANG_FORTRANFIXED;
309 }
310 }
311 while (*p != '\r' && *p != '\n' && *p != '&' && p < eof) p++;
312 if (*p == '&') {
313 p++;
314 // Look for free-form continuation.
315 while (*p == ' ' || *p == '\t') p++;
316 if (*p == '\r' || *p == '\n') {
317 pe = p;
318 while (*pe == '\r' || *pe == '\n' || *pe == ' ' || *pe == '\t') pe++;
319 if (*pe == '&')
320 return LANG_FORTRANFREE;
321 }
322 }
323 while (*p == '\r' || *p == '\n') p++;
324 }
325 return LANG_FORTRANFREE; // might as well be free-form
326 }
327
328 const char *disambiguate_h(SourceFile *sourcefile) {
329 char *p, *pe;
330 int length;
331
332 // If the directory contains a matching *.m file, likely Objective C.
333 length = strlen(sourcefile->filename);
334 if (strcmp(sourcefile->ext, "h") == 0) {
335 char path[length];
336 strncpy(path, sourcefile->filename, length);
337 path[length] = '\0';
338 *(path + length - 1) = 'm';
339 char **filenames = ohcount_sourcefile_get_filenames(sourcefile);
340 if (filenames) {
341 int i;
342 for (i = 0; filenames[i] != NULL; i++)
343 if (strcmp(path, filenames[i]) == 0)
344 return LANG_OBJECTIVE_C;
345 }
346 }
347
348 // Attempt to detect based on file contents.
349 char line[81], buf[81];
350 p = ohcount_sourcefile_get_contents(sourcefile);
351 pe = p;
352 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
353 while (pe < eof) {
354 // Get a line at a time.
355 while (pe < eof && *pe != '\r' && *pe != '\n') pe++;
356 length = (pe - p <= sizeof(line)) ? pe - p : sizeof(line);
357 strncpy(line, p, length);
358 line[length] = '\0';
359 char *eol = line + strlen(line);
360 char *line_end = pe;
361
362 // Look for C++ headers.
363 if (*line == '#') {
364 p = line + 1;
365 while (*p == ' ' || *p == '\t') p++;
366 if (strncmp(p, "include", 7) == 0 &&
367 (*(p + 7) == ' ' || *(p + 7) == '\t')) {
368 // /^#\s*include\s+[<"][^>"]+[>"]/
369 p += 8;
370 while (*p == ' ' || *p == '\t') p++;
371 if (*p == '<' || *p == '"') {
372 // Is the header file a C++ header file?
373 p++;
374 pe = p;
375 while (pe < eol && *pe != '>' && *pe != '"') pe++;
376 length = pe - p;
377 strncpy(buf, p, length);
378 buf[length] = '\0';
379 if (ohcount_hash_is_cppheader(buf, length))
380 return LANG_CPP;
381 // Is the extension for the header file a C++ file?
382 p = pe;
383 while (p > line && *(p - 1) != '.') p--;
384 length = pe - p;
385 strncpy(buf, p, length);
386 buf[length] = '\0';
387 struct ExtensionMap *re = ohcount_hash_language_from_ext(buf, length);
388 if (re && strcmp(re->value, LANG_CPP) == 0)
389 return LANG_CPP;
390 }
391 }
392 }
393
394 // Look for C++ keywords.
395 p = line;
396 while (p < eol) {
397 if (islower(*p) && p != line && !isalnum(*(p - 1)) && *(p - 1) != '_') {
398 pe = p;
399 while (islower(*pe)) pe++;
400 if (!isalnum(*pe) && *pe != '_') {
401 length = pe - p;
402 strncpy(buf, p, length);
403 buf[length] = '\0';
404 if (strcmp(buf, "class") == 0 ||
405 strcmp(buf, "namespace") == 0 ||
406 strcmp(buf, "template") == 0 ||
407 strcmp(buf, "typename") == 0)
408 return LANG_CPP;
409 }
410 p = pe + 1;
411 } else p++;
412 }
413
414 // Next line.
415 pe = line_end;
416 while (*pe == '\r' || *pe == '\n') pe++;
417 p = pe;
418 }
419
420 // Nothing to suggest C++.
421 return LANG_C;
422 }
423
424 const char *disambiguate_in(SourceFile *sourcefile) {
425 char *p, *pe;
426 int length;
427 const char *language = NULL;
428
429 p = sourcefile->filepath;
430 pe = p + strlen(p) - 3;
431 if (strstr(p, ".") <= pe) {
432 // Only if the filename has an extension prior to the .in
433 length = pe - p;
434 char buf[length];
435 strncpy(buf, p, length);
436 buf[length] = '\0';
437 SourceFile *undecorated = ohcount_sourcefile_new(buf);
438 p = ohcount_sourcefile_get_contents(sourcefile);
439 if (!p) {
440 return NULL;
441 }
442 // The filepath without the '.in' extension does not exist on disk. The
443 // sourcefile->diskpath field must be set incase the detector needs to run
444 // 'file -b' on the file.
445 ohcount_sourcefile_set_diskpath(undecorated, sourcefile->filepath);
446 ohcount_sourcefile_set_contents(undecorated, p);
447 char **filenames = ohcount_sourcefile_get_filenames(sourcefile);
448 ohcount_sourcefile_set_filenames(undecorated, filenames);
449 language = ohcount_sourcefile_get_language(undecorated);
450 ohcount_sourcefile_free(undecorated);
451 }
452 return language;
453 }
454
455 const char *disambiguate_inc(SourceFile *sourcefile) {
456 char *p = ohcount_sourcefile_get_contents(sourcefile);
457 char *eof = p + strlen(p);
458 while (p < eof) {
459 if (*p == '\0')
460 return BINARY;
461 else if (*p == '?' && strncmp(p + 1, "php", 3) == 0)
462 return LANG_PHP;
463 p++;
464 }
465 return NULL;
466 }
467
468 const char *disambiguate_m(SourceFile *sourcefile) {
469 char *p, *pe;
470 int length;
471
472 // Attempt to detect based on a weighted heuristic of file contents.
473 int matlab_score = 0;
474 int objective_c_score = 0;
475 int limbo_score = 0;
476 int octave_syntax_detected = 0;
477
478 int i, has_h_headers = 0, has_c_files = 0;
479 char **filenames = ohcount_sourcefile_get_filenames(sourcefile);
480 if (filenames) {
481 for (i = 0; filenames[i] != NULL; i++) {
482 p = filenames[i];
483 pe = p + strlen(p);
484 if (pe - p >= 4) {
485 if (*(pe - 4) == '.' && *(pe - 3) == 'c' &&
486 ((*(pe - 2) == 'p' && *(pe - 1) == 'p') ||
487 (*(pe - 2) == '+' && *(pe - 1) == '+') ||
488 (*(pe - 2) == 'x' && *(pe - 1) == 'x'))) {
489 has_c_files = 1;
490 break; // short circuit
491 }
492 } else if (pe - p >= 3) {
493 if (*(pe - 3) == '.' && *(pe - 2) == 'c' && *(pe - 1) == 'c') {
494 has_c_files = 1;
495 break; // short circuit
496 }
497 } else if (pe - p >= 2) {
498 if (*(pe - 2) == '.') {
499 if (*(pe - 1) == 'h')
500 has_h_headers = 1;
501 else if (*(pe - 1) == 'c' || *(pe - 1) == 'C') {
502 has_c_files = 1;
503 break; // short circuit
504 }
505 }
506 }
507 }
508 }
509 if (has_h_headers && !has_c_files)
510 objective_c_score += 5;
511
512 char line[81], buf[81];
513 p = ohcount_sourcefile_get_contents(sourcefile);
514 pe = p;
515 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
516 while (pe < eof) {
517 // Get a line at a time.
518 while (pe < eof && *pe != '\r' && *pe != '\n') pe++;
519 length = (pe - p <= sizeof(line)) ? pe - p : sizeof(line);
520 strncpy(line, p, length);
521 line[length] = '\0';
522 char *eol = line + strlen(line);
523 char *line_end = pe;
524
525 // Look for tell-tale lines.
526 p = line;
527 while (*p == ' ' || *p == '\t') p++;
528 if (*p == '%') { // Matlab comment
529 matlab_score++;
530 } else if (*p == '#' && strncmp(p, "#import", 7) == 0) { // Objective C
531 objective_c_score++;
532 } else if (*p == '#') { // Limbo or Octave comment
533 while (*p == '#') p++;
534 if (*p == ' ' || *p == '\t') {
535 limbo_score++;
536 matlab_score++;
537 octave_syntax_detected = 1;
538 }
539 } else if (*p == '/' && *(p + 1) == '/' || *(p + 1) == '*') {
540 objective_c_score++; // Objective C comment
541 } else if (*p == '+' || *p == '-') { // Objective C method signature
542 objective_c_score++;
543 } else if (*p == '@' || *p == '#') { // Objective C method signature
544 if (strncmp(p, "@implementation", 15) == 0 ||
545 strncmp(p, "@interface", 10) == 0)
546 objective_c_score++;
547 } else if (strncmp(p, "function", 8) == 0) { // Matlab or Octave function
548 p += 8;
549 while (*p == ' ' || *p == '\t') p++;
550 if (*p == '(')
551 matlab_score++;
552 } else if (strncmp(p, "include", 7) == 0) { // Limbo include
553 // /^include[ \t]+"[^"]+\.m";/
554 p += 7;
555 if (*p == ' ' || *p == '\t') {
556 while (*p == ' ' || *p == '\t') p++;
557 if (*p == '"') {
558 while (*p != '"' && p < eol) p++;
559 if (*p == '"' && *(p - 2) == '.' && *(p - 1) == 'm')
560 limbo_score++;
561 }
562 }
563 }
564
565 // Look for Octave keywords.
566 p = line;
567 while (p < eol) {
568 if (islower(*p) && p != line && !isalnum(*(p - 1))) {
569 pe = p;
570 while (islower(*pe) || *pe == '_') pe++;
571 if (!isalnum(*pe)) {
572 length = pe - p;
573 strncpy(buf, p, length);
574 buf[length] = '\0';
575 if (strcmp(buf, "end_try_catch") == 0 ||
576 strcmp(buf, "end_unwind_protect") == 0 ||
577 strcmp(buf, "endfunction") == 0 ||
578 strcmp(buf, "endwhile") == 0)
579 octave_syntax_detected = 1;
580 }
581 p = pe + 1;
582 } else p++;
583 }
584
585 // Look for Limbo declarations
586 p = line;
587 while (p < eol) {
588 if (*p == ':' && (*(p + 1) == ' ' || *(p + 1) == '\t')) {
589 // /:[ \t]+(module|adt|fn ?\(|con[ \t])/
590 p += 2;
591 if (strncmp(p, "module", 6) == 0 && !isalnum(*(p + 6)) ||
592 strncmp(p, "adt", 3) == 0 && !isalnum(*(p + 3)) ||
593 strncmp(p, "fn", 2) == 0 &&
594 (*(p + 2) == ' ' && *(p + 3) == '(' || *(p + 2) == '(') ||
595 strncmp(p, "con", 3) == 0 &&
596 (*(p + 3) == ' ' || *(p + 3) == '\t'))
597 limbo_score++;
598 } else p++;
599 }
600
601 // Next line.
602 pe = line_end;
603 while (*pe == '\r' || *pe == '\n') pe++;
604 p = pe;
605 }
606
607 if (limbo_score > objective_c_score && limbo_score > matlab_score)
608 return LANG_LIMBO;
609 else if (objective_c_score > matlab_score)
610 return LANG_OBJECTIVE_C;
611 else
612 return octave_syntax_detected ? LANG_OCTAVE : LANG_MATLAB;
613 }
614
615 #define QMAKE_SOURCES_SPACE "SOURCES +="
616 #define QMAKE_SOURCES "SOURCES+="
617 #define QMAKE_CONFIG_SPACE "CONFIG +="
618 #define QMAKE_CONFIG "CONFIG+="
619
620 const char *disambiguate_pro(SourceFile *sourcefile) {
621 char *p = ohcount_sourcefile_get_contents(sourcefile);
622 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
623 for (; p < eof; p++) {
624 if (strncmp(p, QMAKE_SOURCES_SPACE, strlen(QMAKE_SOURCES_SPACE)) == 0 ||
625 strncmp(p, QMAKE_SOURCES, strlen(QMAKE_SOURCES)) == 0 ||
626 strncmp(p, QMAKE_CONFIG_SPACE, strlen(QMAKE_CONFIG_SPACE)) == 0 ||
627 strncmp(p, QMAKE_CONFIG, strlen(QMAKE_CONFIG)) == 0)
628 return LANG_MAKE; // really QMAKE
629 }
630 return LANG_IDL_PVWAVE;
631 }
632
633 const char *disambiguate_st(SourceFile *sourcefile) {
634 char *p, *pe;
635 int length;
636
637 // Attempt to detect based on file contents.
638 int found_assignment = 0, found_block_start = 0, found_block_end = 0;
639
640 char line[81];
641 p = ohcount_sourcefile_get_contents(sourcefile);
642 pe = p;
643 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
644 while (pe < eof) {
645 // Get a line at a time.
646 while (p < eof && *pe != '\r' && *pe != '\n') pe++;
647 length = (pe - p <= sizeof(line)) ? pe - p : sizeof(line);
648 strncpy(line, p, length);
649 line[length] = '\0';
650 char *eol = line + strlen(line);
651 char *line_end = pe;
652
653 for (p = line; p < eol; p++) {
654 if (*p == ':') {
655 p++;
656 while (p < eol && (*p == ' ' || *p == '\t')) p++;
657 if (*p == '=')
658 found_assignment = 1;
659 else if (*p == '[')
660 found_block_start = 1;
661 } else if (*p == ']' && *(p + 1) == '.') found_block_end = 1;
662 if (found_assignment && found_block_start && found_block_end)
663 return LANG_SMALLTALK;
664 }
665
666 // Next line.
667 pe = line_end;
668 while (*pe == '\r' || *pe == '\n') pe++;
669 p = pe;
670 }
671
672 return NULL;
673 }
674
675 int ohcount_is_binary_filename(const char *filename) {
676 char *p = (char *)filename + strlen(filename);
677 while (p > filename && *(p - 1) != '.') p--;
678 if (p > filename) {
679 struct ExtensionMap *re;
680 int length = strlen(p);
681 re = ohcount_hash_language_from_ext(p, length);
682 if (re) return ISBINARY(re->value);
683 // Try the lower-case version of this extension.
684 char lowerext[length];
685 strncpy(lowerext, p, length);
686 lowerext[length] = '\0';
687 for (p = lowerext; p < lowerext + length; p++) *p = tolower(*p);
688 re = ohcount_hash_language_from_ext(lowerext, length);
689 if (re) return ISBINARY(re->value);
690 }
691 return 0;
692 }
+0
-0
.pc/fix_null_dereference.patch/test/detect_files/empty.inc less more
(Empty file)
+0
-133
.pc/fix_null_dereference.patch/test/unit/detector_test.h less more
0 // detector_test.h written by Mitchell Foral. mitchell<att>caladbolg.net.
1 // See COPYING for license information.
2
3 #include <assert.h>
4 #include <stdlib.h>
5 #include <string.h>
6
7 #include "../../src/detector.h"
8 #include "../../src/languages.h"
9 #include "../../src/sourcefile.h"
10
11 #define ASSERT_DETECT(x, y) { \
12 SourceFile *sf = ohcount_sourcefile_new("../detect_files/" y); \
13 const char *lang = ohcount_detect_language(sf); \
14 assert(lang); \
15 assert(strcmp(x, lang) == 0); \
16 ohcount_sourcefile_free(sf); \
17 }
18 #define ASSERT_NODETECT(x) { \
19 SourceFile *sf = ohcount_sourcefile_new("../detect_files/" x); \
20 assert(ohcount_detect_language(sf) == NULL); \
21 ohcount_sourcefile_free(sf); \
22 }
23
24 void test_detector_smalltalk() {
25 ASSERT_DETECT(LANG_SMALLTALK, "example.st");
26 ASSERT_NODETECT("english.st");
27 }
28
29 void test_detector_disambiguate_m() {
30 ASSERT_DETECT(LANG_OBJECTIVE_C, "t1.m");
31 ASSERT_DETECT(LANG_OBJECTIVE_C, "t2.m");
32 ASSERT_DETECT(LANG_OBJECTIVE_C, "TCPSocket.m");
33 ASSERT_DETECT(LANG_OBJECTIVE_C, "foo_objective_c.m");
34 ASSERT_DETECT(LANG_MATLAB, "foo_matlab.m");
35 ASSERT_DETECT(LANG_OCTAVE, "foo_octave.m");
36 }
37
38 void test_detector_disambiguate_in() {
39 ASSERT_NODETECT("empty.in");
40 }
41 void test_detector_disambiguate_pro() {
42 ASSERT_DETECT(LANG_IDL_PVWAVE, "foo.pro");
43 ASSERT_DETECT(LANG_MAKE, "qmake.pro");
44 }
45
46 void test_detector_fortran_fixedfree() {
47 ASSERT_DETECT(LANG_FORTRANFIXED, "fortranfixed.f");
48 ASSERT_DETECT(LANG_FORTRANFREE, "fortranfree.f");
49 }
50
51 void test_detector_detect_polyglot() {
52 ASSERT_DETECT(LANG_C, "foo.c");
53 ASSERT_DETECT(LANG_C, "uses_no_cpp.h");
54 ASSERT_DETECT(LANG_CPP, "uses_cpp_headers.h");
55 ASSERT_DETECT(LANG_CPP, "uses_cpp_stdlib_headers.h");
56 ASSERT_DETECT(LANG_CPP, "uses_cpp_keywords.h");
57 ASSERT_DETECT(LANG_RUBY, "foo.rb");
58 ASSERT_DETECT(LANG_MAKE, "foo.mk");
59 ASSERT_DETECT(LANG_OBJECTIVE_C, "foo_objective_c.h");
60 ASSERT_DETECT(LANG_PHP, "upper_case_php");
61 ASSERT_DETECT(LANG_SMALLTALK, "example.st");
62 ASSERT_DETECT(LANG_VALA, "foo.vala");
63 ASSERT_DETECT(LANG_TEX, "foo.tex");
64 ASSERT_DETECT(LANG_XSLT, "example.xsl");
65 ASSERT_DETECT(LANG_LISP, "core.lisp");
66 ASSERT_DETECT(LANG_DMD, "foo.d");
67 ASSERT_DETECT(LANG_VIM, "foo.vim");
68 ASSERT_DETECT(LANG_EBUILD, "foo.ebuild");
69 ASSERT_DETECT(LANG_EBUILD, "foo.eclass");
70 ASSERT_DETECT(LANG_EXHERES, "foo.exheres-0");
71 ASSERT_DETECT(LANG_EXHERES, "foo.exlib");
72 ASSERT_DETECT(LANG_EIFFEL, "eiffel.e");
73 ASSERT_DETECT(LANG_OCAML, "ocaml.ml");
74 ASSERT_DETECT(LANG_STRATEGO, "stratego.str");
75 ASSERT_DETECT(LANG_R, "foo.R");
76 ASSERT_DETECT(LANG_GLSL, "foo.glsl");
77 ASSERT_DETECT(LANG_GLSL, "foo_glsl.vert");
78 ASSERT_DETECT(LANG_GLSL, "foo_glsl.frag");
79 ASSERT_DETECT(LANG_IDL_PVWAVE, "foo.pro");
80 ASSERT_DETECT(LANG_ASSEMBLER, "foo.z80");
81 ASSERT_DETECT(LANG_PHP, "php.inc");
82 ASSERT_DETECT(LANG_FSHARP, "fs1.fs");
83 }
84
85 void test_detector_upper_case_extensions() {
86 ASSERT_DETECT(LANG_CPP, "foo_upper_case.C");
87 ASSERT_DETECT(LANG_RUBY, "foo_upper_case.RB");
88 }
89
90 void test_detector_no_extensions() {
91 ASSERT_DETECT(LANG_PYTHON, "py_script");
92 ASSERT_DETECT(LANG_RUBY, "ruby_script");
93 ASSERT_DETECT(LANG_SHELL, "bourne_again_script");
94 ASSERT_DETECT(LANG_SHELL, "bash_script");
95 ASSERT_DETECT(LANG_PERL, "perl_w");
96 ASSERT_DETECT(LANG_DMD, "d_script");
97 ASSERT_DETECT(LANG_TCL, "tcl_script");
98 ASSERT_DETECT(LANG_PYTHON, "python.data");
99 ASSERT_DETECT(LANG_PYTHON, "python2.data");
100 }
101
102 void test_detector_csharp_or_clearsilver() {
103 ASSERT_DETECT(LANG_CSHARP, "cs1.cs");
104 ASSERT_DETECT(LANG_CLEARSILVER_TEMPLATE, "clearsilver_template1.cs");
105 }
106
107 void test_detector_basic() {
108 ASSERT_DETECT(LANG_VISUALBASIC, "visual_basic.bas");
109 ASSERT_DETECT(LANG_CLASSIC_BASIC, "classic_basic.b");
110 system("mv ../detect_files/frx1.frx ../detect_files/frx1.frx2");
111 ASSERT_DETECT(LANG_STRUCTURED_BASIC, "visual_basic.bas");
112 ASSERT_DETECT(LANG_STRUCTURED_BASIC, "structured_basic.b");
113 system("mv ../detect_files/frx1.frx2 ../detect_files/frx1.frx");
114 }
115
116 void test_detector_xml_with_custom_extension() {
117 ASSERT_DETECT(LANG_XML, "xml.custom_ext");
118 }
119
120 void all_detector_tests() {
121 test_detector_smalltalk();
122 test_detector_disambiguate_m();
123 test_detector_disambiguate_in();
124 test_detector_disambiguate_pro();
125 test_detector_fortran_fixedfree();
126 test_detector_detect_polyglot();
127 test_detector_upper_case_extensions();
128 test_detector_no_extensions();
129 test_detector_csharp_or_clearsilver();
130 test_detector_basic();
131 test_detector_xml_with_custom_extension();
132 }
+0
-690
.pc/fix_null_dereference_2.patch/src/detector.c less more
0 // detector.c written by Mitchell Foral. mitchell<att>caladbolg.net.
1 // See COPYING for license information.
2
3 #include <ctype.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8
9 #include "detector.h"
10 #include "languages.h"
11 #include "log.h"
12
13 #include "hash/cppheader_hash.h"
14 #include "hash/disambiguatefunc_hash.h"
15 #include "hash/extension_hash.h"
16 #include "hash/filename_hash.h"
17
18 #define ISBINARY(x) (x[0] == '\1')
19 #define ISAMBIGUOUS(x) (x[0] == '\2')
20 #define DISAMBIGUATEWHAT(x) &x[1]
21
22 const char *ohcount_detect_language(SourceFile *sourcefile) {
23 const char *language = NULL;
24 char *p, *pe;
25 int length;
26
27 // Attempt to detect based on file extension.
28 length = strlen(sourcefile->ext);
29 struct ExtensionMap *re = ohcount_hash_language_from_ext(sourcefile->ext,
30 length);
31 if (re) language = re->value;
32 if (language == NULL) {
33 // Try the lower-case version of this extension.
34 char lowerext[length + 1];
35 strncpy(lowerext, sourcefile->ext, length);
36 lowerext[length] = '\0';
37 for (p = lowerext; p < lowerext + length; p++) *p = tolower(*p);
38 struct ExtensionMap *re = ohcount_hash_language_from_ext(lowerext, length);
39 if (re) return re->value;
40 }
41 if (language) {
42 if (ISAMBIGUOUS(language)) {
43 // Call the appropriate function for disambiguation.
44 length = strlen(DISAMBIGUATEWHAT(language));
45 struct DisambiguateFuncsMap *rd =
46 ohcount_hash_disambiguate_func_from_id(DISAMBIGUATEWHAT(language),
47 length);
48 if (rd) return rd->value(sourcefile);
49 } else return ISBINARY(language) ? NULL : language;
50 }
51
52 // Attempt to detect based on filename.
53 length = strlen(sourcefile->filename);
54 struct FilenameMap *rf =
55 ohcount_hash_language_from_filename(sourcefile->filename, length);
56 if (rf) return rf->value;
57
58 char line[81] = { '\0' }, buf[81];
59
60 // Attempt to detect using Emacs mode line (/^-\*-\s*mode[\s:]*\w/i).
61 p = ohcount_sourcefile_get_contents(sourcefile);
62 pe = p;
63 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
64 while (pe < eof) {
65 // Get the contents of the first line.
66 while (pe < eof && *pe != '\r' && *pe != '\n') pe++;
67 length = (pe - p <= sizeof(line)) ? pe - p : sizeof(line);
68 strncpy(line, p, length);
69 line[length] = '\0';
70 if (*line == '#' && *(line + 1) == '!') {
71 // First line was sh-bang; loop to get contents of second line.
72 while (*pe == '\r' || *pe == '\n') pe++;
73 p = pe;
74 } else break;
75 }
76 char *eol = line + strlen(line);
77 for (p = line; p < eol; p++) *p = tolower(*p);
78 p = strstr(line, "-*-");
79 if (p) {
80 p += 3;
81 while (*p == ' ' || *p == '\t') p++;
82 if (strncmp(p, "mode", 4) == 0) {
83 p += 4;
84 while (*p == ' ' || *p == '\t' || *p == ':') p++;
85 }
86 pe = p;
87 while (isalnum(*pe)) pe++;
88 length = pe - p;
89 strncpy(buf, p, length);
90 buf[length] = '\0';
91 struct LanguageMap *rl = ohcount_hash_language_from_name(buf, length);
92 if (rl) return rl->name;
93 }
94
95 // Attempt to detect based on Unix 'file' command.
96 int tmpfile = 0;
97 char *path = sourcefile->filepath;
98 if (sourcefile->diskpath)
99 path = sourcefile->diskpath;
100 if (access(path, F_OK) != 0) { // create temporary file
101 path = malloc(21);
102 strncpy(path, "/tmp/ohcount_XXXXXXX", 20);
103 *(path + 21) = '\0';
104 int fd = mkstemp(path);
105 char *contents = ohcount_sourcefile_get_contents(sourcefile);
106 log_it("contents:");
107 log_it(contents);
108 length = contents ? strlen(contents) : 0;
109 write(fd, contents, length);
110 close(fd);
111 tmpfile = 1;
112 }
113 char command[strlen(path) + 11];
114 sprintf(command, "file -b '%s'", path);
115 FILE *f = popen(command, "r");
116 if (f) {
117 fgets(line, sizeof(line), f);
118 char *eol = line + strlen(line);
119 for (p = line; p < eol; p++) *p = tolower(*p);
120 p = strstr(line, "script text");
121 if (p && p == line) { // /^script text(?: executable)? for \w/
122 p = strstr(line, "for ");
123 if (p) {
124 p += 4;
125 pe = p;
126 while (isalnum(*pe)) pe++;
127 length = pe - p;
128 strncpy(buf, p, length);
129 buf[length] = '\0';
130 struct LanguageMap *rl = ohcount_hash_language_from_name(buf, length);
131 if (rl) language = rl->name;
132 }
133 } else if (p) { // /(\w+)(?: -\w+)* script text/
134 do {
135 p--;
136 pe = p;
137 while (*p == ' ') p--;
138 while (p != line && isalnum(*(p - 1))) p--;
139 if (p != line && *(p - 1) == '-') p--;
140 } while (*p == '-'); // Skip over any switches.
141 length = pe - p;
142 strncpy(buf, p, length);
143 buf[length] = '\0';
144 struct LanguageMap *rl = ohcount_hash_language_from_name(buf, length);
145 if (rl) language = rl->name;
146 } else if (strstr(line, "xml")) language = LANG_XML;
147 pclose(f);
148 if (tmpfile) {
149 remove(path);
150 free(path);
151 }
152 if (language) return language;
153 }
154
155 return NULL;
156 }
157
158 const char *disambiguate_aspx(SourceFile *sourcefile) {
159 char *p = ohcount_sourcefile_get_contents(sourcefile);
160 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
161 for (; p < eof; p++) {
162 // /<%@\s*Page[^>]+Language="VB"[^>]+%>/
163 p = strstr(p, "<%@");
164 if (!p)
165 break;
166 char *pe = strstr(p, "%>");
167 if (p && pe) {
168 p += 3;
169 const int length = pe - p;
170 char buf[length];
171 strncpy(buf, p, length);
172 buf[length] = '\0';
173 char *eol = buf + strlen(buf);
174 for (p = buf; p < eol; p++) *p = tolower(*p);
175 p = buf;
176 while (*p == ' ' || *p == '\t') p++;
177 if (strncmp(p, "page", 4) == 0) {
178 p += 4;
179 if (strstr(p, "language=\"vb\""))
180 return LANG_VB_ASPX;
181 }
182 }
183 }
184 return LANG_CS_ASPX;
185 }
186
187 const char *disambiguate_b(SourceFile *sourcefile) {
188 char *p = ohcount_sourcefile_get_contents(sourcefile);
189 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
190 while (p < eof) {
191 // /(implement[ \t])|(include[ \t]+"[^"]*";)|
192 // ((return|break|continue).*;|(pick|case).*\{)/
193 if (strncmp(p, "implement", 9) == 0 &&
194 (*(p + 9) == ' ' || *(p + 9) == '\t'))
195 return LANG_LIMBO;
196 else if (strncmp(p, "include", 7) == 0 &&
197 (*(p + 7) == ' ' || *(p + 7) == '\t')) {
198 p += 7;
199 while (*p == ' ' || *p == '\t') p++;
200 if (*p == '"') {
201 while (*p != '"' && p < eof) p++;
202 if (*p == '"' && *(p + 1) == ';')
203 return LANG_LIMBO;
204 }
205 } else if (strncmp(p, "return", 6) == 0 ||
206 strncmp(p, "break", 5) == 0 ||
207 strncmp(p, "continue", 8) == 0) {
208 if (strstr(p, ";"))
209 return LANG_LIMBO;
210 } else if (strncmp(p, "pick", 4) == 0 ||
211 strncmp(p, "case", 4) == 0) {
212 if (strstr(p, "{"))
213 return LANG_LIMBO;
214 }
215 p++;
216 }
217 return disambiguate_basic(sourcefile);
218 }
219
220 const char *disambiguate_basic(SourceFile *sourcefile) {
221 char *p, *pe;
222 int length;
223
224 // Attempt to detect based on file contents.
225 char line[81];
226 p = ohcount_sourcefile_get_contents(sourcefile);
227 pe = p;
228 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
229 while (pe < eof) {
230 // Get a line at a time.
231 while (pe < eof && *pe != '\r' && *pe != '\n') pe++;
232 length = (pe - p <= sizeof(line)) ? pe - p : sizeof(line);
233 strncpy(line, p, length);
234 line[length] = '\0';
235 char *line_end = pe;
236
237 p = line;
238 if (isdigit(*p)) {
239 // /^\d+\s+\w/
240 p++;
241 while (isdigit(*p)) p++;
242 if (*p == ' ' || *p == '\t') {
243 p++;
244 while (*p == ' ' || *p == '\t') p++;
245 if (isalnum(*p))
246 return LANG_CLASSIC_BASIC;
247 }
248 }
249
250 // Next line.
251 pe = line_end;
252 while (*pe == '\r' || *pe == '\n') pe++;
253 p = pe;
254 }
255
256 // Attempt to detect from associated VB files in file context.
257 char **filenames = ohcount_sourcefile_get_filenames(sourcefile);
258 if (filenames) {
259 int i;
260 for (i = 0; filenames[i] != NULL; i++) {
261 pe = filenames[i] + strlen(filenames[i]);
262 p = pe;
263 while (p > filenames[i] && *(p - 1) != '.') p--;
264 length = pe - p;
265 if (length == 3 &&
266 (strncmp(p, "frm", length) == 0 ||
267 strncmp(p, "frx", length) == 0 ||
268 strncmp(p, "vba", length) == 0 ||
269 strncmp(p, "vbp", length) == 0 ||
270 strncmp(p, "vbs", length) == 0)) {
271 return LANG_VISUALBASIC;
272 }
273 }
274 }
275
276 return LANG_STRUCTURED_BASIC;
277 }
278
279 const char *disambiguate_cs(SourceFile *sourcefile) {
280 // Attempt to detect based on file contents.
281 char *contents = ohcount_sourcefile_get_contents(sourcefile);
282 if (contents && strstr(contents, "<?cs"))
283 return LANG_CLEARSILVER_TEMPLATE;
284 else
285 return LANG_CSHARP;
286 }
287
288 const char *disambiguate_fortran(SourceFile *sourcefile) {
289 char *p, *pe;
290
291 p = ohcount_sourcefile_get_contents(sourcefile);
292 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
293 while (p < eof) {
294 if (*p == ' ' && p + 5 < eof) {
295 int i;
296 for (i = 1; i <= 5; i++)
297 if (!isdigit(*(p + i)) && *(p + i) != ' ')
298 return LANG_FORTRANFIXED; // definately not f77
299 // Possibly fixed (doesn't match /^\s*\d+\s*$/).
300 pe = p;
301 while (*pe == ' ' || *pe == '\t') pe++;
302 if (pe - p <= 5) {
303 if (!isdigit(*pe))
304 return LANG_FORTRANFIXED;
305 while (isdigit(*pe)) pe++;
306 while (*pe == ' ' || *pe == '\t') pe++;
307 if (*pe != '\r' && *pe != '\n' && pe - p == 5)
308 return LANG_FORTRANFIXED;
309 }
310 }
311 while (*p != '\r' && *p != '\n' && *p != '&' && p < eof) p++;
312 if (*p == '&') {
313 p++;
314 // Look for free-form continuation.
315 while (*p == ' ' || *p == '\t') p++;
316 if (*p == '\r' || *p == '\n') {
317 pe = p;
318 while (*pe == '\r' || *pe == '\n' || *pe == ' ' || *pe == '\t') pe++;
319 if (*pe == '&')
320 return LANG_FORTRANFREE;
321 }
322 }
323 while (*p == '\r' || *p == '\n') p++;
324 }
325 return LANG_FORTRANFREE; // might as well be free-form
326 }
327
328 const char *disambiguate_h(SourceFile *sourcefile) {
329 char *p, *pe;
330 int length;
331
332 // If the directory contains a matching *.m file, likely Objective C.
333 length = strlen(sourcefile->filename);
334 if (strcmp(sourcefile->ext, "h") == 0) {
335 char path[length];
336 strncpy(path, sourcefile->filename, length);
337 path[length] = '\0';
338 *(path + length - 1) = 'm';
339 char **filenames = ohcount_sourcefile_get_filenames(sourcefile);
340 if (filenames) {
341 int i;
342 for (i = 0; filenames[i] != NULL; i++)
343 if (strcmp(path, filenames[i]) == 0)
344 return LANG_OBJECTIVE_C;
345 }
346 }
347
348 // Attempt to detect based on file contents.
349 char line[81], buf[81];
350 p = ohcount_sourcefile_get_contents(sourcefile);
351 pe = p;
352 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
353 while (pe < eof) {
354 // Get a line at a time.
355 while (pe < eof && *pe != '\r' && *pe != '\n') pe++;
356 length = (pe - p <= sizeof(line)) ? pe - p : sizeof(line);
357 strncpy(line, p, length);
358 line[length] = '\0';
359 char *eol = line + strlen(line);
360 char *line_end = pe;
361
362 // Look for C++ headers.
363 if (*line == '#') {
364 p = line + 1;
365 while (*p == ' ' || *p == '\t') p++;
366 if (strncmp(p, "include", 7) == 0 &&
367 (*(p + 7) == ' ' || *(p + 7) == '\t')) {
368 // /^#\s*include\s+[<"][^>"]+[>"]/
369 p += 8;
370 while (*p == ' ' || *p == '\t') p++;
371 if (*p == '<' || *p == '"') {
372 // Is the header file a C++ header file?
373 p++;
374 pe = p;
375 while (pe < eol && *pe != '>' && *pe != '"') pe++;
376 length = pe - p;
377 strncpy(buf, p, length);
378 buf[length] = '\0';
379 if (ohcount_hash_is_cppheader(buf, length))
380 return LANG_CPP;
381 // Is the extension for the header file a C++ file?
382 p = pe;
383 while (p > line && *(p - 1) != '.') p--;
384 length = pe - p;
385 strncpy(buf, p, length);
386 buf[length] = '\0';
387 struct ExtensionMap *re = ohcount_hash_language_from_ext(buf, length);
388 if (re && strcmp(re->value, LANG_CPP) == 0)
389 return LANG_CPP;
390 }
391 }
392 }
393
394 // Look for C++ keywords.
395 p = line;
396 while (p < eol) {
397 if (islower(*p) && p != line && !isalnum(*(p - 1)) && *(p - 1) != '_') {
398 pe = p;
399 while (islower(*pe)) pe++;
400 if (!isalnum(*pe) && *pe != '_') {
401 length = pe - p;
402 strncpy(buf, p, length);
403 buf[length] = '\0';
404 if (strcmp(buf, "class") == 0 ||
405 strcmp(buf, "namespace") == 0 ||
406 strcmp(buf, "template") == 0 ||
407 strcmp(buf, "typename") == 0)
408 return LANG_CPP;
409 }
410 p = pe + 1;
411 } else p++;
412 }
413
414 // Next line.
415 pe = line_end;
416 while (*pe == '\r' || *pe == '\n') pe++;
417 p = pe;
418 }
419
420 // Nothing to suggest C++.
421 return LANG_C;
422 }
423
424 const char *disambiguate_in(SourceFile *sourcefile) {
425 char *p, *pe;
426 int length;
427 const char *language = NULL;
428
429 p = sourcefile->filepath;
430 pe = p + strlen(p) - 3;
431 if (strstr(p, ".") <= pe) {
432 // Only if the filename has an extension prior to the .in
433 length = pe - p;
434 char buf[length];
435 strncpy(buf, p, length);
436 buf[length] = '\0';
437 SourceFile *undecorated = ohcount_sourcefile_new(buf);
438 p = ohcount_sourcefile_get_contents(sourcefile);
439 // The filepath without the '.in' extension does not exist on disk. The
440 // sourcefile->diskpath field must be set incase the detector needs to run
441 // 'file -b' on the file.
442 ohcount_sourcefile_set_diskpath(undecorated, sourcefile->filepath);
443 ohcount_sourcefile_set_contents(undecorated, p);
444 char **filenames = ohcount_sourcefile_get_filenames(sourcefile);
445 ohcount_sourcefile_set_filenames(undecorated, filenames);
446 language = ohcount_sourcefile_get_language(undecorated);
447 ohcount_sourcefile_free(undecorated);
448 }
449 return language;
450 }
451
452 const char *disambiguate_inc(SourceFile *sourcefile) {
453 char *p = ohcount_sourcefile_get_contents(sourcefile);
454 char *eof = p + strlen(p);
455 while (p < eof) {
456 if (*p == '\0')
457 return BINARY;
458 else if (*p == '?' && strncmp(p + 1, "php", 3) == 0)
459 return LANG_PHP;
460 p++;
461 }
462 return NULL;
463 }
464
465 const char *disambiguate_m(SourceFile *sourcefile) {
466 char *p, *pe;
467 int length;
468
469 // Attempt to detect based on a weighted heuristic of file contents.
470 int matlab_score = 0;
471 int objective_c_score = 0;
472 int limbo_score = 0;
473 int octave_syntax_detected = 0;
474
475 int i, has_h_headers = 0, has_c_files = 0;
476 char **filenames = ohcount_sourcefile_get_filenames(sourcefile);
477 if (filenames) {
478 for (i = 0; filenames[i] != NULL; i++) {
479 p = filenames[i];
480 pe = p + strlen(p);
481 if (pe - p >= 4) {
482 if (*(pe - 4) == '.' && *(pe - 3) == 'c' &&
483 ((*(pe - 2) == 'p' && *(pe - 1) == 'p') ||
484 (*(pe - 2) == '+' && *(pe - 1) == '+') ||
485 (*(pe - 2) == 'x' && *(pe - 1) == 'x'))) {
486 has_c_files = 1;
487 break; // short circuit
488 }
489 } else if (pe - p >= 3) {
490 if (*(pe - 3) == '.' && *(pe - 2) == 'c' && *(pe - 1) == 'c') {
491 has_c_files = 1;
492 break; // short circuit
493 }
494 } else if (pe - p >= 2) {
495 if (*(pe - 2) == '.') {
496 if (*(pe - 1) == 'h')
497 has_h_headers = 1;
498 else if (*(pe - 1) == 'c' || *(pe - 1) == 'C') {
499 has_c_files = 1;
500 break; // short circuit
501 }
502 }
503 }
504 }
505 }
506 if (has_h_headers && !has_c_files)
507 objective_c_score += 5;
508
509 char line[81], buf[81];
510 p = ohcount_sourcefile_get_contents(sourcefile);
511 pe = p;
512 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
513 while (pe < eof) {
514 // Get a line at a time.
515 while (pe < eof && *pe != '\r' && *pe != '\n') pe++;
516 length = (pe - p <= sizeof(line)) ? pe - p : sizeof(line);
517 strncpy(line, p, length);
518 line[length] = '\0';
519 char *eol = line + strlen(line);
520 char *line_end = pe;
521
522 // Look for tell-tale lines.
523 p = line;
524 while (*p == ' ' || *p == '\t') p++;
525 if (*p == '%') { // Matlab comment
526 matlab_score++;
527 } else if (*p == '#' && strncmp(p, "#import", 7) == 0) { // Objective C
528 objective_c_score++;
529 } else if (*p == '#') { // Limbo or Octave comment
530 while (*p == '#') p++;
531 if (*p == ' ' || *p == '\t') {
532 limbo_score++;
533 matlab_score++;
534 octave_syntax_detected = 1;
535 }
536 } else if (*p == '/' && *(p + 1) == '/' || *(p + 1) == '*') {
537 objective_c_score++; // Objective C comment
538 } else if (*p == '+' || *p == '-') { // Objective C method signature
539 objective_c_score++;
540 } else if (*p == '@' || *p == '#') { // Objective C method signature
541 if (strncmp(p, "@implementation", 15) == 0 ||
542 strncmp(p, "@interface", 10) == 0)
543 objective_c_score++;
544 } else if (strncmp(p, "function", 8) == 0) { // Matlab or Octave function
545 p += 8;
546 while (*p == ' ' || *p == '\t') p++;
547 if (*p == '(')
548 matlab_score++;
549 } else if (strncmp(p, "include", 7) == 0) { // Limbo include
550 // /^include[ \t]+"[^"]+\.m";/
551 p += 7;
552 if (*p == ' ' || *p == '\t') {
553 while (*p == ' ' || *p == '\t') p++;
554 if (*p == '"') {
555 while (*p != '"' && p < eol) p++;
556 if (*p == '"' && *(p - 2) == '.' && *(p - 1) == 'm')
557 limbo_score++;
558 }
559 }
560 }
561
562 // Look for Octave keywords.
563 p = line;
564 while (p < eol) {
565 if (islower(*p) && p != line && !isalnum(*(p - 1))) {
566 pe = p;
567 while (islower(*pe) || *pe == '_') pe++;
568 if (!isalnum(*pe)) {
569 length = pe - p;
570 strncpy(buf, p, length);
571 buf[length] = '\0';
572 if (strcmp(buf, "end_try_catch") == 0 ||
573 strcmp(buf, "end_unwind_protect") == 0 ||
574 strcmp(buf, "endfunction") == 0 ||
575 strcmp(buf, "endwhile") == 0)
576 octave_syntax_detected = 1;
577 }
578 p = pe + 1;
579 } else p++;
580 }
581
582 // Look for Limbo declarations
583 p = line;
584 while (p < eol) {
585 if (*p == ':' && (*(p + 1) == ' ' || *(p + 1) == '\t')) {
586 // /:[ \t]+(module|adt|fn ?\(|con[ \t])/
587 p += 2;
588 if (strncmp(p, "module", 6) == 0 && !isalnum(*(p + 6)) ||
589 strncmp(p, "adt", 3) == 0 && !isalnum(*(p + 3)) ||
590 strncmp(p, "fn", 2) == 0 &&
591 (*(p + 2) == ' ' && *(p + 3) == '(' || *(p + 2) == '(') ||
592 strncmp(p, "con", 3) == 0 &&
593 (*(p + 3) == ' ' || *(p + 3) == '\t'))
594 limbo_score++;
595 } else p++;
596 }
597
598 // Next line.
599 pe = line_end;
600 while (*pe == '\r' || *pe == '\n') pe++;
601 p = pe;
602 }
603
604 if (limbo_score > objective_c_score && limbo_score > matlab_score)
605 return LANG_LIMBO;
606 else if (objective_c_score > matlab_score)
607 return LANG_OBJECTIVE_C;
608 else
609 return octave_syntax_detected ? LANG_OCTAVE : LANG_MATLAB;
610 }
611
612 #define QMAKE_SOURCES_SPACE "SOURCES +="
613 #define QMAKE_SOURCES "SOURCES+="
614 #define QMAKE_CONFIG_SPACE "CONFIG +="
615 #define QMAKE_CONFIG "CONFIG+="
616
617 const char *disambiguate_pro(SourceFile *sourcefile) {
618 char *p = ohcount_sourcefile_get_contents(sourcefile);
619 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
620 for (; p < eof; p++) {
621 if (strncmp(p, QMAKE_SOURCES_SPACE, strlen(QMAKE_SOURCES_SPACE)) == 0 ||
622 strncmp(p, QMAKE_SOURCES, strlen(QMAKE_SOURCES)) == 0 ||
623 strncmp(p, QMAKE_CONFIG_SPACE, strlen(QMAKE_CONFIG_SPACE)) == 0 ||
624 strncmp(p, QMAKE_CONFIG, strlen(QMAKE_CONFIG)) == 0)
625 return LANG_MAKE; // really QMAKE
626 }
627 return LANG_IDL_PVWAVE;
628 }
629
630 const char *disambiguate_st(SourceFile *sourcefile) {
631 char *p, *pe;
632 int length;
633
634 // Attempt to detect based on file contents.
635 int found_assignment = 0, found_block_start = 0, found_block_end = 0;
636
637 char line[81];
638 p = ohcount_sourcefile_get_contents(sourcefile);
639 pe = p;
640 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
641 while (pe < eof) {
642 // Get a line at a time.
643 while (p < eof && *pe != '\r' && *pe != '\n') pe++;
644 length = (pe - p <= sizeof(line)) ? pe - p : sizeof(line);
645 strncpy(line, p, length);
646 line[length] = '\0';
647 char *eol = line + strlen(line);
648 char *line_end = pe;
649
650 for (p = line; p < eol; p++) {
651 if (*p == ':') {
652 p++;
653 while (p < eol && (*p == ' ' || *p == '\t')) p++;
654 if (*p == '=')
655 found_assignment = 1;
656 else if (*p == '[')
657 found_block_start = 1;
658 } else if (*p == ']' && *(p + 1) == '.') found_block_end = 1;
659 if (found_assignment && found_block_start && found_block_end)
660 return LANG_SMALLTALK;
661 }
662
663 // Next line.
664 pe = line_end;
665 while (*pe == '\r' || *pe == '\n') pe++;
666 p = pe;
667 }
668
669 return NULL;
670 }
671
672 int ohcount_is_binary_filename(const char *filename) {
673 char *p = (char *)filename + strlen(filename);
674 while (p > filename && *(p - 1) != '.') p--;
675 if (p > filename) {
676 struct ExtensionMap *re;
677 int length = strlen(p);
678 re = ohcount_hash_language_from_ext(p, length);
679 if (re) return ISBINARY(re->value);
680 // Try the lower-case version of this extension.
681 char lowerext[length];
682 strncpy(lowerext, p, length);
683 lowerext[length] = '\0';
684 for (p = lowerext; p < lowerext + length; p++) *p = tolower(*p);
685 re = ohcount_hash_language_from_ext(lowerext, length);
686 if (re) return ISBINARY(re->value);
687 }
688 return 0;
689 }
+0
-0
.pc/fix_null_dereference_2.patch/test/detect_files/empty.in less more
(Empty file)
+0
-129
.pc/fix_null_dereference_2.patch/test/unit/detector_test.h less more
0 // detector_test.h written by Mitchell Foral. mitchell<att>caladbolg.net.
1 // See COPYING for license information.
2
3 #include <assert.h>
4 #include <stdlib.h>
5 #include <string.h>
6
7 #include "../../src/detector.h"
8 #include "../../src/languages.h"
9 #include "../../src/sourcefile.h"
10
11 #define ASSERT_DETECT(x, y) { \
12 SourceFile *sf = ohcount_sourcefile_new("../detect_files/" y); \
13 const char *lang = ohcount_detect_language(sf); \
14 assert(lang); \
15 assert(strcmp(x, lang) == 0); \
16 ohcount_sourcefile_free(sf); \
17 }
18 #define ASSERT_NODETECT(x) { \
19 SourceFile *sf = ohcount_sourcefile_new("../detect_files/" x); \
20 assert(ohcount_detect_language(sf) == NULL); \
21 ohcount_sourcefile_free(sf); \
22 }
23
24 void test_detector_smalltalk() {
25 ASSERT_DETECT(LANG_SMALLTALK, "example.st");
26 ASSERT_NODETECT("english.st");
27 }
28
29 void test_detector_disambiguate_m() {
30 ASSERT_DETECT(LANG_OBJECTIVE_C, "t1.m");
31 ASSERT_DETECT(LANG_OBJECTIVE_C, "t2.m");
32 ASSERT_DETECT(LANG_OBJECTIVE_C, "TCPSocket.m");
33 ASSERT_DETECT(LANG_OBJECTIVE_C, "foo_objective_c.m");
34 ASSERT_DETECT(LANG_MATLAB, "foo_matlab.m");
35 ASSERT_DETECT(LANG_OCTAVE, "foo_octave.m");
36 }
37
38 void test_detector_disambiguate_pro() {
39 ASSERT_DETECT(LANG_IDL_PVWAVE, "foo.pro");
40 ASSERT_DETECT(LANG_MAKE, "qmake.pro");
41 }
42
43 void test_detector_fortran_fixedfree() {
44 ASSERT_DETECT(LANG_FORTRANFIXED, "fortranfixed.f");
45 ASSERT_DETECT(LANG_FORTRANFREE, "fortranfree.f");
46 }
47
48 void test_detector_detect_polyglot() {
49 ASSERT_DETECT(LANG_C, "foo.c");
50 ASSERT_DETECT(LANG_C, "uses_no_cpp.h");
51 ASSERT_DETECT(LANG_CPP, "uses_cpp_headers.h");
52 ASSERT_DETECT(LANG_CPP, "uses_cpp_stdlib_headers.h");
53 ASSERT_DETECT(LANG_CPP, "uses_cpp_keywords.h");
54 ASSERT_DETECT(LANG_RUBY, "foo.rb");
55 ASSERT_DETECT(LANG_MAKE, "foo.mk");
56 ASSERT_DETECT(LANG_OBJECTIVE_C, "foo_objective_c.h");
57 ASSERT_DETECT(LANG_PHP, "upper_case_php");
58 ASSERT_DETECT(LANG_SMALLTALK, "example.st");
59 ASSERT_DETECT(LANG_VALA, "foo.vala");
60 ASSERT_DETECT(LANG_TEX, "foo.tex");
61 ASSERT_DETECT(LANG_XSLT, "example.xsl");
62 ASSERT_DETECT(LANG_LISP, "core.lisp");
63 ASSERT_DETECT(LANG_DMD, "foo.d");
64 ASSERT_DETECT(LANG_VIM, "foo.vim");
65 ASSERT_DETECT(LANG_EBUILD, "foo.ebuild");
66 ASSERT_DETECT(LANG_EBUILD, "foo.eclass");
67 ASSERT_DETECT(LANG_EXHERES, "foo.exheres-0");
68 ASSERT_DETECT(LANG_EXHERES, "foo.exlib");
69 ASSERT_DETECT(LANG_EIFFEL, "eiffel.e");
70 ASSERT_DETECT(LANG_OCAML, "ocaml.ml");
71 ASSERT_DETECT(LANG_STRATEGO, "stratego.str");
72 ASSERT_DETECT(LANG_R, "foo.R");
73 ASSERT_DETECT(LANG_GLSL, "foo.glsl");
74 ASSERT_DETECT(LANG_GLSL, "foo_glsl.vert");
75 ASSERT_DETECT(LANG_GLSL, "foo_glsl.frag");
76 ASSERT_DETECT(LANG_IDL_PVWAVE, "foo.pro");
77 ASSERT_DETECT(LANG_ASSEMBLER, "foo.z80");
78 ASSERT_DETECT(LANG_PHP, "php.inc");
79 ASSERT_DETECT(LANG_FSHARP, "fs1.fs");
80 }
81
82 void test_detector_upper_case_extensions() {
83 ASSERT_DETECT(LANG_CPP, "foo_upper_case.C");
84 ASSERT_DETECT(LANG_RUBY, "foo_upper_case.RB");
85 }
86
87 void test_detector_no_extensions() {
88 ASSERT_DETECT(LANG_PYTHON, "py_script");
89 ASSERT_DETECT(LANG_RUBY, "ruby_script");
90 ASSERT_DETECT(LANG_SHELL, "bourne_again_script");
91 ASSERT_DETECT(LANG_SHELL, "bash_script");
92 ASSERT_DETECT(LANG_PERL, "perl_w");
93 ASSERT_DETECT(LANG_DMD, "d_script");
94 ASSERT_DETECT(LANG_TCL, "tcl_script");
95 ASSERT_DETECT(LANG_PYTHON, "python.data");
96 ASSERT_DETECT(LANG_PYTHON, "python2.data");
97 }
98
99 void test_detector_csharp_or_clearsilver() {
100 ASSERT_DETECT(LANG_CSHARP, "cs1.cs");
101 ASSERT_DETECT(LANG_CLEARSILVER_TEMPLATE, "clearsilver_template1.cs");
102 }
103
104 void test_detector_basic() {
105 ASSERT_DETECT(LANG_VISUALBASIC, "visual_basic.bas");
106 ASSERT_DETECT(LANG_CLASSIC_BASIC, "classic_basic.b");
107 system("mv ../detect_files/frx1.frx ../detect_files/frx1.frx2");
108 ASSERT_DETECT(LANG_STRUCTURED_BASIC, "visual_basic.bas");
109 ASSERT_DETECT(LANG_STRUCTURED_BASIC, "structured_basic.b");
110 system("mv ../detect_files/frx1.frx2 ../detect_files/frx1.frx");
111 }
112
113 void test_detector_xml_with_custom_extension() {
114 ASSERT_DETECT(LANG_XML, "xml.custom_ext");
115 }
116
117 void all_detector_tests() {
118 test_detector_smalltalk();
119 test_detector_disambiguate_m();
120 test_detector_disambiguate_pro();
121 test_detector_fortran_fixedfree();
122 test_detector_detect_polyglot();
123 test_detector_upper_case_extensions();
124 test_detector_no_extensions();
125 test_detector_csharp_or_clearsilver();
126 test_detector_basic();
127 test_detector_xml_with_custom_extension();
128 }
+0
-162
.pc/rbconfig.patch/build less more
0 #!/usr/bin/env bash
1 # Build script for Ohcount.
2 # Written by Mitchell Foral. mitchell<att>caladbolg.net.
3
4 # Options
5 # Change these for your system configuration.
6 if [ `uname` != "Darwin" ]
7 then
8 # Linux
9 INC_DIR=
10 LIB_DIR=
11
12 if [ `uname` == "FreeBSD" ]
13 then
14 INC_DIR=/usr/local/include
15 LIB_DIR=/usr/local/lib
16 fi
17
18 # You shouldn't have to change the following.
19 CFLAGS=-O3
20 CFLAGS="$CFLAGS -DTMP_FILES_ARE_DT_UNKNOWN" # workaround bug on centos/SF servers
21 WARN="-Wall -Wno-pointer-to-int-cast -Wno-parentheses"
22 SHARED=-shared
23 SHARED_NAME=libohcount.so
24 RB_SHARED=-shared
25 RB_SHARED_NAME=ohcount.so
26 else
27 # Mac OSX
28 INC_DIR=/opt/local/include
29 LIB_DIR=/opt/local/lib
30 # You shouldn't have to change the following.
31 CFLAGS="-fno-common -g"
32 WARN="-Wall -Wno-parentheses"
33 SHARED="-dynamiclib -L$LIB_DIR -lpcre"
34 SHARED_NAME=libohcount.dylib
35 RB_SHARED="-dynamic -bundle -lruby"
36 RB_SHARED_NAME=ohcount.bundle
37 fi
38
39 # C compiler and flags
40 cc="gcc -fPIC -g $CFLAGS $WARN -I$INC_DIR -L$LIB_DIR"
41
42 # Ohcount source files
43 files="src/sourcefile.c \
44 src/detector.c \
45 src/licenses.c \
46 src/parser.o \
47 src/loc.c \
48 src/log.c \
49 src/diff.c \
50 src/parsed_language.c \
51 src/hash/language_hash.c"
52
53 # If any src/hash/*.gperf file is newer than the header files (which were
54 # presumably generated together), regenerate the headers.
55 build_hash_headers()
56 {
57 if [[ -z `ls src/hash/ | grep "_hash.h$"` ||
58 ! -z `find src/hash/*.gperf -newer src/hash/parser_hash.h` ]]
59 then
60 echo "Generating hash headers"
61 sh -c "cd src/hash/ && ./generate_headers" || exit 1
62 fi
63 }
64
65 # If src/parser.o does not exist, or if there are Ragel parsers or parser
66 # header files newer than the existing parser.o, recompile parser.o.
67 build_parser_o()
68 {
69 if [[ ! -f src/parser.o ||
70 ! -z `find src/parsers/*.{h,rl} -newer src/parser.o` ]]
71 then
72 bash -c "cd src/parsers/ && bash ./compile" || exit 1
73 echo "Building src/parser.c (will take a while)"
74 bash -c "$cc -c src/parser.c -o src/parser.o" || exit 1
75 fi
76 }
77
78 build_shared()
79 {
80 build_hash_headers
81 build_parser_o
82 if [[ ! -f src/$SHARED_NAME ||
83 ! -z `find src/*.{h,c} -newer src/$SHARED_NAME` ]]
84 then
85 echo "Building shared library"
86 sh -c "$cc $SHARED $files -o src/$SHARED_NAME" || exit 1
87 fi
88 }
89
90 build_ohcount()
91 {
92 build_hash_headers
93 build_parser_o
94 echo "Building Ohcount"
95 mkdir -p bin/
96 sh -c "$cc src/ohcount.c $files -o bin/ohcount -lpcre" || exit 1
97 }
98
99 build_test_suite()
100 {
101 build_hash_headers
102 build_parser_o
103 echo "Building test suite"
104 sh -c "$cc test/unit/all_tests.c $files -o test/unit/run_tests -lpcre" \
105 || exit 1
106 }
107
108 run_test_suite()
109 {
110 echo "Running test suite"
111 echo "disabled test suite, does not work"
112 }
113
114 build_ruby_bindings()
115 {
116 arch=`ruby -rmkmf -e 'print Config::expand(CONFIG["arch"])'`
117 echo "Generating Ruby bindings for $arch"
118 sh -c "swig -ruby -o ruby/ohcount_wrap.c ruby/ohcount.i" || exit 1
119 mkdir -p ruby/$arch
120 sh -c "$cc $RB_SHARED ruby/ohcount_wrap.c $files -o ruby/$arch/$RB_SHARED_NAME \
121 -I`ruby -rmkmf -e 'print Config::expand(CONFIG["archdir"])'` \
122 -lpcre" || exit 1
123 sh -c "cd test/unit/ruby && ruby ruby_test.rb" || exit 1
124 }
125
126 if [ $# -eq 0 ] || [ $1 == "all" ]
127 then
128 build_ohcount
129 build_test_suite
130 run_test_suite
131 echo $success
132 elif [ $1 == "shared" ]
133 then
134 build_shared
135 echo "Build successful; $SHARED_NAME is in src/"
136 elif [ $1 == "ohcount" ]
137 then
138 build_ohcount
139 echo "Build successful; ohcount is in bin/"
140 elif [ $1 == "tests" ]
141 then
142 build_test_suite
143 run_test_suite
144 elif [ $1 == "ruby" ]
145 then
146 build_ruby_bindings
147 echo "Build successful; $RB_SHARED_NAME is in ruby/$arch"
148 elif [ $1 == "clean" ]
149 then
150 rm -f bin/ohcount
151 rm -f test/unit/run_tests
152 rm -f src/parser.o
153 rm -f src/parsers/*.h
154 rm -f src/hash/*.h
155 rm -f src/hash/*.c
156 rm -f src/$SHARED_NAME
157 rm -f ruby/$RB_SHARED_NAME
158 rm -rf ruby/`ruby -rmkmf -e 'print Config::expand(CONFIG["arch"])'`/*
159 else
160 echo "Usage: build [all|ohcount|shared|tests|ruby|clean]"
161 fi
+0
-181
.pc/txx_support.patch/src/hash/extensions.gperf less more
0 %{
1 #include "../languages.h"
2
3 #define BINARY "\1"
4 #define DISAMBIGUATE(x) ("\2" x)
5 %}
6 struct ExtensionMap { const char *key; const char *value; };
7 %%
8 C, LANG_CPP
9 H, LANG_CPP
10 ada, LANG_ADA
11 adb, LANG_ADA
12 ads, LANG_ADA
13 aiff, BINARY
14 as, LANG_ACTIONSCRIPT
15 ascx, DISAMBIGUATE("aspx")
16 asm, LANG_ASSEMBLER
17 aspx, DISAMBIGUATE("aspx")
18 au, BINARY
19 avi, BINARY
20 awk, LANG_AWK
21 b, DISAMBIGUATE("b")
22 bas, DISAMBIGUATE("basic")
23 bat, LANG_BAT
24 bi, DISAMBIGUATE("basic")
25 bmp, BINARY
26 bmx, LANG_BLITZMAX
27 boo, LANG_BOO
28 c, LANG_C
29 c++, LANG_CPP
30 cache, BINARY
31 cc, LANG_CPP
32 cmake, LANG_CMAKE
33 com, LANG_DCL
34 cpp, LANG_CPP
35 cs, DISAMBIGUATE("cs")
36 csproj, LANG_XML
37 css, LANG_CSS
38 ctp, LANG_PHP
39 cxx, LANG_CPP
40 d, LANG_DMD
41 dat, BINARY
42 di, LANG_DMD
43 doc, BINARY
44 dylan, LANG_DYLAN
45 e, LANG_EIFFEL
46 ebuild, LANG_EBUILD
47 eclass, LANG_EBUILD
48 el, LANG_EMACSLISP
49 erl, LANG_ERLANG
50 exheres-0, LANG_EXHERES
51 exlib, LANG_EXHERES
52 f, DISAMBIGUATE("fortran")
53 f03, DISAMBIGUATE("fortran")
54 f77, DISAMBIGUATE("fortran")
55 f90, DISAMBIGUATE("fortran")
56 f95, DISAMBIGUATE("fortran")
57 factor, LANG_FACTOR
58 frag, LANG_GLSL
59 frm, LANG_VISUALBASIC
60 frx, LANG_VISUALBASIC
61 fs, LANG_FSHARP
62 ftn, DISAMBIGUATE("fortran")
63 gif, BINARY
64 glsl, LANG_GLSL
65 groovy, LANG_GROOVY
66 gz, BINARY
67 h, DISAMBIGUATE("h")
68 h++, LANG_CPP
69 haml, LANG_HAML
70 hh, LANG_CPP
71 hpp, LANG_CPP
72 hrl, LANG_ERLANG
73 hs, LANG_HASKELL
74 htm, LANG_HTML
75 html, LANG_HTML
76 hx, LANG_HAXE
77 hxx, LANG_CPP
78 icns, BINARY
79 in, DISAMBIGUATE("in")
80 inc, DISAMBIGUATE("inc")
81 j, LANG_OBJECTIVE_J
82 jar, BINARY
83 java, LANG_JAVA
84 jpeg, BINARY
85 jpg, BINARY
86 js, LANG_JAVASCRIPT
87 jsp, LANG_JSP
88 kdebuild-1, LANG_EBUILD
89 latex, LANG_TEX
90 lisp, LANG_LISP
91 lsp, LANG_LISP
92 ltx, LANG_TEX
93 lua, LANG_LUA
94 m, DISAMBIGUATE("m")
95 m4a, BINARY
96 mf, LANG_METAFONT
97 mk, LANG_MAKE
98 ml, LANG_OCAML
99 ml4, LANG_OCAML
100 mli, LANG_OCAML
101 mm, LANG_OBJECTIVE_C
102 mov, BINARY
103 mp, LANG_METAPOST_WITH_TEX
104 mp3, BINARY
105 mpg, BINARY
106 mxml, LANG_MXML
107 nix, LANG_NIX
108 nse, LANG_LUA
109 ogg, BINARY
110 p6, LANG_PERL
111 pas, LANG_PASCAL
112 perl, LANG_PERL
113 pdf, BINARY
114 ph, LANG_PERL
115 php, LANG_PHP
116 php3, LANG_PHP
117 php4, LANG_PHP
118 php5, LANG_PHP
119 pike, LANG_PIKE
120 pl, LANG_PERL
121 pm, LANG_PERL
122 pmc, LANG_C
123 pmod, LANG_PIKE
124 png, BINARY
125 pnt, BINARY
126 pod, LANG_PERL
127 pp, LANG_PASCAL
128 ppt, BINARY
129 pro, DISAMBIGUATE("pro")
130 py, LANG_PYTHON
131 qt, BINARY
132 r, LANG_R
133 ra, BINARY
134 rb, LANG_RUBY
135 rex, LANG_REXX
136 rexx, LANG_REXX
137 rhtml, LANG_RHTML
138 s, LANG_ASSEMBLER
139 sc, LANG_SCHEME
140 scala, LANG_SCALA
141 sce, LANG_SCILAB
142 sci, LANG_SCILAB
143 scm, LANG_SCHEME
144 sh, LANG_SHELL
145 sls, LANG_SCHEME
146 sps, LANG_SCHEME
147 sql, LANG_SQL
148 ss, LANG_SCHEME
149 st, DISAMBIGUATE("st")
150 str, LANG_STRATEGO
151 svg, BINARY
152 svgz, BINARY
153 svn, BINARY
154 swf, BINARY
155 t, LANG_PERL
156 tar, BINARY
157 tcl, LANG_TCL
158 tex, LANG_TEX
159 tgz, BINARY
160 tif, BINARY
161 tiff, BINARY
162 tpl, LANG_HTML
163 vala, LANG_VALA
164 vb, LANG_VISUALBASIC
165 vba, LANG_VISUALBASIC
166 vbs, LANG_VISUALBASIC
167 vert, LANG_GLSL
168 vhd, LANG_VHDL
169 vhdl, LANG_VHDL
170 vim, LANG_VIM
171 wav, BINARY
172 xaml, LANG_XAML
173 xls, BINARY
174 xlw, BINARY
175 xml, LANG_XML
176 xs, LANG_C
177 xsd, LANG_XMLSCHEMA
178 xsl, LANG_XSLT
179 z80, LANG_ASSEMBLER
180 zip, BINARY
+0
-90
README less more
0 == Ohcount
1
2 NOTE: THE PRIMARY DOCUMENTATION FOR OHCOUNT IS EXTRACTED FROM SOURCE CODE
3 BY DOXYGEN. FOR THE MOST UP-TO-DATE DOCS, PLEASE SEE BELOW FOR INFO
4 ON BUILDING AND REFERING TO THE DOXYGEN DOCS.
5
6 Ohloh/SourceForge's source code line counter.
7
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License Version 2 as
10 published by the Free Software Foundation.
11
12 Ohcount is specifically licensed under GPL v2.0, and no later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
21
22 == Overview
23
24 Ohcount is a library for counting lines of source code.
25 It was originally developed at Ohloh, and is used to generate
26 the reports at www.ohloh.net.
27
28 Ohcount supports multiple languages within a single file: for example,
29 a complex HTML document might include regions of both CSS and JavaScript.
30
31 Ohcount has two main components: a detector which determines the primary
32 language family used by a particular source file, and a parser which
33 provides a line-by-line breakdown of the contents of a source file.
34
35 Ohcount includes a command line tool that allows you to count individual
36 files or whole directory trees. It also allows you to find source code
37 files by language family, or to create a detailed annotation of an
38 individual source file.
39
40 Ohcount includes a Ruby binding which allows you to directly access its
41 language detection features from a Ruby application.
42
43 == System Requirements
44
45 Ohcount is supported on Mac OS X 10.4 and 10.5 and Ubuntu 8.04 LTS. Other Linux
46 environments should also work, but your mileage may vary.
47
48 Ohcount does not support Windows.
49
50 Ohcount targets Ruby 1.8.6. The build script requires a bash shell. You
51 also need a C compiler to build the native extensions.
52
53 == Source Code ==
54
55 Ohcount source code is available as a Git repository:
56
57 git clone git://github.com/andyverprauskus/ohcount.git
58
59 == Doc files ==
60
61 To build the more extensive Doxygen docs, do
62 > cd doc
63 > Doxygen Doxyfile
64
65 After building the docs, view them with a browser by opening doc/html/index.html.
66 On a mac, you can install Doxygen with "sudo port install Doxygen".
67 On Debian/Ubuntu, install with "sudo apt-get instal doxygen".
68
69 == Building Ohcount ==
70
71 You will need ragel 6.3 or higher, bash, pcre, gcc (version 4.1.2 or greater) and SWIG to build ohcount. Once you have them, go to the top directory of ohcount and type:
72
73 > bash build
74 or > ./build
75
76 == Using Ohcount ==
77
78 Once you've building ohcount, the executable program will be at bin/ohcount. The most basic use is to count lines of code in a directory tree, run:
79 "ohcount" to count the current directory and source code in any child directories
80
81 == For additional docs, including how to add a new language, see the Doxygen docs ==
82
83 Particularly, for instructions on adding a new language, follow the instructions at doc/html/detector_doc.html
84 Read http://labs.ohloh.net/ohcount/wiki/HowToSubmitPatches for information about having your patch accepted.
85
86
87 DEPENDENCIES
88 ============
89 SWIG, pcre, ragel, bash
0 Ohcount
1 =======
2
3 Ohloh's source code line counter.
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License Version 2 as
7 published by the Free Software Foundation.
8
9 License
10 -------
11
12 Ohcount is specifically licensed under GPL v2.0, and no later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
21
22 Overview
23 --------
24
25 Ohcount is a library for counting lines of source code.
26 It was originally developed at Ohloh, and is used to generate
27 the reports at www.openhub.net.
28
29 Ohcount supports multiple languages within a single file: for example,
30 a complex HTML document might include regions of both CSS and JavaScript.
31
32 Ohcount has two main components: a detector which determines the primary
33 language family used by a particular source file, and a parser which
34 provides a line-by-line breakdown of the contents of a source file.
35
36 Ohcount includes a command line tool that allows you to count individual
37 files or whole directory trees. It also allows you to find source code
38 files by language family, or to create a detailed annotation of an
39 individual source file.
40
41 Ohcount includes a Ruby binding which allows you to directly access its
42 language detection features from a Ruby application.
43
44 System Requirements
45 -------------------
46
47 Ohcount is supported on Ubuntu 14.04 LTS. Other Linux
48 environments should also work, but your mileage may vary.
49
50 Ohcount does not support Windows.
51
52 Ohcount targets Ruby 1.9.3. The build script requires a bash shell. You
53 also need a C compiler to build the native extensions.
54
55 Source Code
56 -----------
57
58 Ohcount source code is available as a Git repository:
59
60 git clone git://github.com/blackducksw/ohcount.git
61
62 Building Ohcount
63 ----------------
64
65 You will need ragel 6.8 or higher, bash, gperf, libpcre3-dev, libmagic-dev, gcc (version 4.8.2 or greater)
66 and SWIG (2.0.11). Once you have them, go to the top directory of ohcount and run
67
68 ```
69 ./build
70 ```
71
72 Using Ohcount
73 -------------
74
75 Once you've built ohcount, the executable program will be at bin/ohcount. The most basic use is to count lines of code in a directory tree. run:
76
77 ```
78 bin/ohcount
79 ```
80
81 Ohcount support several options. Run `ohcount --help` for more information.
82
83 Building Ruby and Python Libraries
84 ----------------------------------
85
86 To build the ruby wrapper:
87
88 ```
89 ./build ruby
90 ```
91
92 To build the python wrapper, run
93
94 ```
95 python python/setup.py build
96 python python/setup.py install
97 ```
98
99 The python wrapper is currently unsupported.
1717
1818 # You shouldn't have to change the following.
1919 CFLAGS=-O3
20 CFLAGS="$CFLAGS -DTMP_FILES_ARE_DT_UNKNOWN" # workaround bug on centos/SF servers
2120 WARN="-Wall -Wno-pointer-to-int-cast -Wno-parentheses"
2221 SHARED=-shared
2322 SHARED_NAME=libohcount.so
3837
3938 # C compiler and flags
4039 cc="gcc -fPIC -g $CFLAGS $WARN -I$INC_DIR -L$LIB_DIR"
40
41 # ARCHITECTURE
42 arch=`ruby/print_arch`
4143
4244 # Ohcount source files
4345 files="src/sourcefile.c \
9395 build_parser_o
9496 echo "Building Ohcount"
9597 mkdir -p bin/
96 sh -c "$cc src/ohcount.c $files -o bin/ohcount -lpcre" || exit 1
98 sh -c "$cc src/ohcount.c $files -o bin/ohcount -lpcre -lmagic" || exit 1
9799 }
98100
99101 build_test_suite()
101103 build_hash_headers
102104 build_parser_o
103105 echo "Building test suite"
104 sh -c "$cc test/unit/all_tests.c $files -o test/unit/run_tests -lpcre" \
106 sh -c "$cc test/unit/all_tests.c $files -o test/unit/run_tests -lpcre -lmagic" \
105107 || exit 1
106108 }
107109
108110 run_test_suite()
109111 {
110112 echo "Running test suite"
111 echo "disabled test suite, does not work"
113 sh -c "cd test/unit/ && ./run_tests"
112114 }
115
116 RUBY_HEADER_DIR=`ruby -rmkmf -e 'print RbConfig::expand(CONFIG["rubyhdrdir"])'`
117 rbconfig_arch=`ruby -rmkmf -e 'print RbConfig::expand(CONFIG["arch"])'`
118 RUBY_CONFIG_DIR="$RUBY_HEADER_DIR/$rbconfig_arch"
113119
114120 build_ruby_bindings()
115121 {
116 arch=`ruby -rmkmf -e 'print RbConfig::expand(RbConfig::CONFIG["arch"])'`
117122 echo "Generating Ruby bindings for $arch"
118123 sh -c "swig -ruby -o ruby/ohcount_wrap.c ruby/ohcount.i" || exit 1
119124 mkdir -p ruby/$arch
120125 sh -c "$cc $RB_SHARED ruby/ohcount_wrap.c $files -o ruby/$arch/$RB_SHARED_NAME \
121 -I`ruby -rmkmf -e 'print RbConfig::expand(RbConfig::CONFIG["archdir"])'` \
122 -lpcre" || exit 1
126 -I$RUBY_HEADER_DIR -I$RUBY_CONFIG_DIR \
127 -lpcre -lmagic" || exit 1
123128 sh -c "cd test/unit/ruby && ruby ruby_test.rb" || exit 1
124129 }
125130
128133 build_ohcount
129134 build_test_suite
130135 run_test_suite
136 build_ruby_bindings
131137 echo $success
132138 elif [ $1 == "shared" ]
133139 then
155161 rm -f src/hash/*.c
156162 rm -f src/$SHARED_NAME
157163 rm -f ruby/$RB_SHARED_NAME
158 rm -rf ruby/`ruby -rmkmf -e 'print RbConfig::expand(RbConfig::CONFIG["arch"])'`/*
164 rm -rf ruby/$arch/*
165 rm -f ruby/ohcount_wrap.c
159166 else
160167 echo "Usage: build [all|ohcount|shared|tests|ruby|clean]"
161168 fi
+0
-120
debian/changelog less more
0 ohcount (3.0.0-8.4) unstable; urgency=medium
1
2 * Standards-Version updated to 4.1.3
3 * Update of Vcs-*
4 * Update of the homepage
5 * Add a watch file
6
7 -- Sylvestre Ledru <sylvestre@debian.org> Sun, 14 Jan 2018 19:03:49 +0100
8
9 ohcount (3.0.0-8.3) unstable; urgency=medium
10
11 * Non-maintainer upload.
12 * Remove ruby files from ohcount-doc, which only get installed
13 when building for Arch: all. (Closes: #818239)
14
15 -- Christian Hofstaedtler <zeha@debian.org> Thu, 22 Dec 2016 06:54:28 +0000
16
17 ohcount (3.0.0-8.2) unstable; urgency=medium
18
19 * Non-maintainer upload.
20 * Source-ful, binary-less upload to get rid of /ruby directory.
21 Probably somehow my fault? (Closes: #818239)
22
23 -- Christian Hofstaedtler <zeha@debian.org> Sun, 17 Jul 2016 19:58:32 +0000
24
25 ohcount (3.0.0-8.1) unstable; urgency=medium
26
27 * Non-maintainer upload.
28 * Fix build system being broken by removal of deprecated "Config"
29 object in Ruby 2.2. (Closes: #805674)
30
31 -- Christian Hofstaedtler <zeha@debian.org> Tue, 01 Mar 2016 22:02:31 +0100
32
33 ohcount (3.0.0-8) unstable; urgency=low
34
35 * Remove the explicit dependency on ruby 1.8
36 Thanks to Jonas Genannt (Closes: #733724)
37 * Switch from cdbs to dh. Thanks to Jonas Genannt
38 * Standards-Version updated to 3.9.5
39
40 -- Sylvestre Ledru <sylvestre@debian.org> Thu, 16 Jan 2014 16:26:45 +0100
41
42 ohcount (3.0.0-7) unstable; urgency=low
43
44 * Standards-Version updated to 3.9.4
45 * libdifflcs-ruby dep renamed to ruby-diff-lcs (Closes: #707792)
46 * Remove Torsten from the uploaders (I have been DD for a while :)
47 * ACK NMU (thanks btw)
48
49 -- Sylvestre Ledru <sylvestre@debian.org> Sat, 11 May 2013 19:17:57 +0200
50
51 ohcount (3.0.0-6.1) unstable; urgency=low
52
53 * Non-maintainer upload.
54 * Add dependency on file (Closes: #677494).
55
56 -- Luk Claes <luk@debian.org> Wed, 04 Jul 2012 17:18:12 +0000
57
58 ohcount (3.0.0-6) unstable; urgency=low
59
60 * Update some issues with the documentation (Closes: #650685)
61
62 -- Sylvestre Ledru <sylvestre@debian.org> Sat, 10 Dec 2011 19:38:15 +0100
63
64 ohcount (3.0.0-5) unstable; urgency=low
65
66 * Oups. Plug back the patches
67 * Manpage of ohcount added
68
69 -- Sylvestre Ledru <sylvestre@debian.org> Fri, 30 Sep 2011 21:37:34 +0200
70
71 ohcount (3.0.0-4) unstable; urgency=low
72
73 * Support of the txx extension (considered as C++). Thanks to Sébastien Dinot
74 for the patch.
75 * Switch to dpkg-source 3.0 (quilt) format
76 * Standards-Version updated to version 3.9.2
77 * Fix debian-rules-uses-deprecated-makefile lintian warning
78
79 -- Sylvestre Ledru <sylvestre@debian.org> Mon, 26 Sep 2011 13:42:49 +0200
80
81 ohcount (3.0.0-3) unstable; urgency=low
82
83 * Standards-Version updated to version 3.9.1
84 * Fix a seg fault when checking lintian source code. Thanks to
85 Raphael Geissert for investigating for me. (Closes: #608837)
86 (LP: #605631)
87 * Fix lintian warning copyright-refers-to-deprecated-bsd-license-file
88
89 -- Sylvestre Ledru <sylvestre@debian.org> Sat, 15 Jan 2011 09:34:05 +0100
90
91 ohcount (3.0.0-2) unstable; urgency=low
92
93 * Missing dependency (Closes: #558491)
94
95 -- Sylvestre Ledru <sylvestre@debian.org> Sun, 29 Nov 2009 18:19:46 +0100
96
97 ohcount (3.0.0-1) unstable; urgency=low
98
99 * New upstream release
100 * New package ohcount-doc added
101 * Homepage updated
102 * Vcs-* added
103 * Many changes on the debian/rules due to a refactoring from upstream which
104 has been done (patches are now obsolete or upstream)
105 * Upstream has redeveloped ohcount with C (instead of ruby). (Closes: #542892)
106 * Update of the watch file
107 * Repack script updated (upstream has a .so)
108 * Standards-Version updated to version 3.8.3
109 * Change of my email address since I am now DD
110 * Standards-Version updated to 3.8.3
111 * DM-Upload-Allowed removed
112
113 -- Sylvestre Ledru <sylvestre@debian.org> Fri, 27 Nov 2009 11:22:21 +0100
114
115 ohcount (2.0.1-1) unstable; urgency=low
116
117 * Initial release (Closes: #523006)
118
119 -- Sylvestre Ledru <sylvestre.ledru@inria.fr> Tue, 07 Apr 2009 20:18:38 +0200
+0
-1
debian/compat less more
0 7
+0
-40
debian/control less more
0 Source: ohcount
1 Section: utils
2 Priority: optional
3 Maintainer: Sylvestre Ledru <sylvestre@debian.org>
4 Build-Depends: debhelper (>= 7), libpcre3-dev, gem2deb, rake,
5 ragel (>= 6.3), ruby-diff-lcs, doxygen, gperf, file
6 Standards-Version: 4.1.3
7 Homepage: https://github.com/blackducksoftware/ohcount
8 Vcs-Git: https://salsa.debian.org/debian/ohcount.git
9 Vcs-Browser: https://salsa.debian.org/debian/ohcount
10 XS-Ruby-Versions: all
11
12 Package: ohcount
13 XB-Ruby-Versions: ${ruby:Versions}
14 Architecture: any
15 Depends: ruby | ruby-interpreter, ${shlibs:Depends}, ${misc:Depends},
16 ruby-diff-lcs, file
17 Suggests: ohcount-doc
18 Description: Source code line counter
19 Ohcount supports over 70 popular programming languages.
20 Ohcount does more than just count lines of code. It can also detect
21 popular open source licenses such as GPL within a large directory of source
22 code. It can also detect code that targets a particular programming API,
23 such as Win32 or KDE.
24 Ohcount is the line counter which powers http://www.ohloh.net/
25 .
26
27 Package: ohcount-doc
28 Section: doc
29 Architecture: all
30 Depends: ${shlibs:Depends}, ${misc:Depends}
31 Description: Source code line counter - Documentation
32 Ohcount supports over 70 popular programming languages.
33 Ohcount does more than just count lines of code. It can also detect
34 popular open source licenses such as GPL within a large directory of source
35 code. It can also detect code that targets a particular programming API,
36 such as Win32 or KDE.
37 Ohcount is the line counter which powers http://www.ohloh.net/
38 .
39 This package contains the documentation.
+0
-132
debian/copyright less more
0 This package was debianized by Sylvestre Ledru <sylvestre.ledru@inria.fr> on
1 Tue, 07 Apr 2009 20:18:38 +0200.
2
3 It was downloaded from <http://labs.ohloh.net/ohcount/>
4
5 Upstream Author:
6
7 Ohloh <info@ohloh.net>
8
9 Copyright:
10
11 Copyright (C) 2007-2009 Ohloh
12
13 License:
14
15 This program is free software; you can redistribute it and/or modify
16 it under the terms of the GNU General Public License as published by
17 the Free Software Foundation; either version 2 of the License, or
18 (at your option) any later version.
19
20 This program is distributed in the hope that it will be useful,
21 but WITHOUT ANY WARRANTY; without even the implied warranty of
22 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 GNU General Public License for more details.
24
25 You should have received a copy of the GNU General Public License along
26 with this program; if not, write to the Free Software Foundation, Inc.,
27 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
28
29 The full text of the license can be found in
30 `/usr/share/common-licenses/GPL-2'.
31
32 The Debian packaging is (C) 2009, Sylvestre Ledru <sylvestre.ledru@inria.fr> and
33 is licensed under the GPL, see `/usr/share/common-licenses/GPL'.
34
35 ohcount incorporates some piece of code in order to test during build time
36 its capabilities. These files are not included in the binary.
37
38
39 Files: test/expected_dir/haxe1.hx test/src_dir/haxe1.hx
40
41 Copyright:
42 Thomas Pfeiffer - kiroukou
43 Niel Drummond
44
45 License:
46 Copyright the original author or authors.
47 Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
48 you may not use this file except in compliance with the License.
49 You may obtain a copy of the License at
50 http://www.mozilla.org/MPL/MPL-1.1.html
51 Unless required by applicable law or agreed to in writing, software
52 distributed under the License is distributed on an "AS IS" BASIS,
53 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
54 See the License for the specific language governing permissions and
55 limitations under the License.
56
57 Files: test/src_dir/pascal2.pp test/expected_dir/pascal2.pp
58
59 Copyright:
60 Simon Steele 1998-2000
61
62 License:
63 BSD
64 Redistribution and use in source and binary forms, with or without
65 modification, are permitted provided that the following conditions are
66 met:
67
68 * Redistributions of source code must retain the above copyright
69 notice, this list of conditions and the following disclaimer.
70 * Redistributions in binary form must reproduce the above copyright
71 notice, this list of conditions and the following disclaimer in the
72 documentation and/or other materials provided with the distribution.
73 * Neither the name of the <ORGANIZATION> nor the names of its
74 contributors may be used to endorse or promote products derived from
75 this software without specific prior written permission.
76
77 Files: test/src_dir/js1.js test/expected_dir/js1.js
78
79 Copyright:
80 2005-2008 Sam Stephenson
81
82 License:
83 MIT
84
85 Permission is hereby granted, free of charge, to any person obtaining a copy
86 of this software and associated documentation files (the "Software"), to deal
87 in the Software without restriction, including without limitation the rights
88 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
89 copies of the Software, and to permit persons to whom the Software is
90 furnished to do so, subject to the following conditions:
91
92 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
93 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
94 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
95 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
96 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
97 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
98 SOFTWARE.
99
100
101 Files: test/src_dir/foo.ebuild test/detect_files/foo.ebuild
102
103 License:
104 GPL-2
105
106 Files: test/src_dir/as1.as test/expected_dir/as1.as
107
108 Copyright:
109 Sean Chatman and Garrett Woodworth 2008
110
111 License:
112 MIT
113
114 Files: test/src_dir/perl_module.pm test/expected_dir/perl_module.pm
115
116 Copyright:
117 Audrey Tang 2003-2007
118
119 License:
120 This program is free software; you can redistribute it and/or modify it
121 under the same terms as Perl itself.
122
123 a) the GNU General Public License as published by the Free Software
124 Foundation; either version 1, or (at your option) any later
125 version, or
126
127 b) the "Artistic License" which comes with Perl.
128
129 On Debian GNU/Linux systems, the complete text of the GNU General
130 Public License can be found in `/usr/share/common-licenses/GPL' and
131 the Artistic Licence in `/usr/share/common-licenses/Artistic'.
+0
-9
debian/ohcount-doc.doc-base less more
0 Document: ohcount
1 Title: Debian ohcount Manual
2 Author: Ohloh
3 Abstract: ohcount manual
4 Section: Programming/Ruby
5
6 Format: HTML
7 Index: /usr/share/doc/ohcount-doc/index.html
8 Files: /usr/share/doc/ohcount-doc/*
+0
-1
debian/ohcount-doc.docs less more
0 README
+0
-67
debian/ohcount.1 less more
0 .\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.39.4.
1 .TH OHCOUNT "1" "September 2011" "ohcount 3.0.0" "User Commands"
2 .SH NAME
3 ohcount \- manual page for ohcount 3.0.0
4 .SH SYNOPSIS
5 .B ohcount
6 [\fIoption\fR] [\fIpaths\fR...]
7 .SH DESCRIPTION
8 Ohloh source code line counter command line tool.
9 .IP
10 http://www.ohloh.net/
11 .SS "[option] can be one of the following:"
12 .HP
13 \fB\-a\fR, \fB\-\-annotate\fR
14 .HP
15 \fB\-d\fR, \fB\-\-detect\fR
16 .HP
17 \fB\-h\fR, \fB\-\-help\fR
18 .HP
19 \fB\-i\fR, \fB\-\-individual\fR
20 .HP
21 \fB\-l\fR, \fB\-\-license\fR
22 .HP
23 \fB\-re\fR
24 .HP
25 \fB\-s\fR, \fB\-\-summary\fR
26 .PP
27 \fB\-a\fR, \fB\-\-annotate\fR Show annotated source code
28 .IP
29 The contents of all source code files found within the given
30 paths will be emitted to stdout. Each line will be prefixed with
31 a tab\-delimited language name and semantic categorization (code,
32 comment, or blank).
33 .PP
34 \fB\-d\fR, \fB\-\-detect\fR Find source code files
35 .IP
36 Recursively find all source code files within the given paths.
37 For each source code file found, the file name will be emitted to
38 stdout prefixed with a tab\-delimited language name.
39 .PP
40 \fB\-h\fR, \fB\-\-help\fR Display this message
41 .PP
42 \fB\-i\fR, \fB\-\-individual\fR Count lines of code per file
43 .IP
44 Count lines in all source code files within the given paths, and
45 emit a report of the lines of code, comments, and blanks in each
46 language per file.
47 .PP
48 \fB\-l\fR, \fB\-\-license\fR
49 .IP
50 Displays detected licensing information contained in each source
51 code file.
52 .PP
53 \fB\-re\fR
54 .IP
55 Prints raw entity information to the screen (mainly for debugging).
56 .PP
57 \fB\-s\fR, \fB\-\-summary\fR Count lines of code (default)
58 .IP
59 Count lines in all source code files within the given paths, and
60 emit a report of the total number of lines of code, comments,
61 and blanks in each language. This is the default action.
62 .PP
63 [paths] can refer to any number of individual files or directories.
64 .IP
65 Directories will be probed recursively. If no path is given,
66 the current directory will be used.
+0
-2
debian/ohcount.manpages less more
0 debian/ohcount.1
1
+0
-1
debian/orig-tar.exclude less more
0 *.so
+0
-19
debian/orig-tar.sh less more
0 #!/bin/sh -e
1
2 # called by uscan with '--upstream-version' <version> <file>
3 DIR=ohcount-$2
4 TAR=../ohcount_$2.orig.tar.gz
5
6 # clean up the upstream tarball
7 tar zxf $3
8 # Remove vendor/ because it is including
9 tar -c -z -X debian/orig-tar.exclude -f $TAR $DIR/
10 rm -rf $DIR
11
12 # move to directory 'tarballs'
13 if [ -r .svn/deb-layout ]; then
14 . .svn/deb-layout
15 mv $TAR $origDir
16 echo "moved $TAR to $origDir"
17 fi
18
+0
-15
debian/patches/disabled_test_suite.patch less more
0 Description: disable test suite on build time, does not work
1 Author: Jonas Genannt <jonas.genannt@capi2name.de>
2 Forwarded: not-needed
3
4 --- a/build
5 +++ b/build
6 @@ -109,7 +109,7 @@ build_test_suite()
7 run_test_suite()
8 {
9 echo "Running test suite"
10 - sh -c "cd test/unit/ && ./run_tests"
11 + echo "disabled test suite, does not work"
12 }
13
14 build_ruby_bindings()
+0
-58
debian/patches/fix_null_dereference.patch less more
0 From a6783afcf61f18e9f1aef3e2655b30af7501c902 Mon Sep 17 00:00:00 2001
1 From: Robin Luckey <robin@ohloh.net>
2 Date: Thu, 1 Oct 2009 14:32:16 -0700
3 Subject: [PATCH] [FIX] Avoid null dereference in disambiguate_inc()
4
5 ---
6 src/detector.c | 18 ++++++++++--------
7 test/unit/detector_test.h | 1 +
8 2 files changed, 11 insertions(+), 8 deletions(-)
9 create mode 100644 test/detect_files/empty.inc
10
11 diff --git a/src/detector.c b/src/detector.c
12 index 4d0e1f4..9b4d8d2 100644
13 --- a/src/detector.c
14 +++ b/src/detector.c
15 @@ -452,14 +452,16 @@ const char *disambiguate_in(SourceFile *sourcefile) {
16
17 const char *disambiguate_inc(SourceFile *sourcefile) {
18 char *p = ohcount_sourcefile_get_contents(sourcefile);
19 - char *eof = p + strlen(p);
20 - while (p < eof) {
21 - if (*p == '\0')
22 - return BINARY;
23 - else if (*p == '?' && strncmp(p + 1, "php", 3) == 0)
24 - return LANG_PHP;
25 - p++;
26 - }
27 + if (p) {
28 + char *eof = p + strlen(p);
29 + while (p < eof) {
30 + if (*p == '\0')
31 + return BINARY;
32 + else if (*p == '?' && strncmp(p + 1, "php", 3) == 0)
33 + return LANG_PHP;
34 + p++;
35 + }
36 + }
37 return NULL;
38 }
39
40 diff --git a/test/detect_files/empty.inc b/test/detect_files/empty.inc
41 new file mode 100644
42 index 0000000..e69de29
43 diff --git a/test/unit/detector_test.h b/test/unit/detector_test.h
44 index cd36b6d..628b6cc 100644
45 --- a/test/unit/detector_test.h
46 +++ b/test/unit/detector_test.h
47 @@ -77,6 +77,7 @@ void test_detector_detect_polyglot() {
48 ASSERT_DETECT(LANG_IDL_PVWAVE, "foo.pro");
49 ASSERT_DETECT(LANG_ASSEMBLER, "foo.z80");
50 ASSERT_DETECT(LANG_PHP, "php.inc");
51 + ASSERT_NODETECT("empty.inc");
52 ASSERT_DETECT(LANG_FSHARP, "fs1.fs");
53 }
54
55 --
56 1.7.0.1
57
+0
-53
debian/patches/fix_null_dereference_2.patch less more
0 From c0b28d67f27f6e954c93dabd71d098854896d679 Mon Sep 17 00:00:00 2001
1 From: Robin Luckey <robin@ohloh.net>
2 Date: Thu, 1 Oct 2009 15:43:42 -0700
3 Subject: [PATCH] [FIX] Null dereference error in disambiguate_in()
4
5 ---
6 src/detector.c | 3 +++
7 test/unit/detector_test.h | 4 ++++
8 2 files changed, 7 insertions(+), 0 deletions(-)
9 create mode 100644 test/detect_files/empty.in
10
11 diff --git a/src/detector.c b/src/detector.c
12 index 9b4d8d2..863b379 100644
13 --- a/src/detector.c
14 +++ b/src/detector.c
15 @@ -437,6 +437,9 @@ const char *disambiguate_in(SourceFile *sourcefile) {
16 buf[length] = '\0';
17 SourceFile *undecorated = ohcount_sourcefile_new(buf);
18 p = ohcount_sourcefile_get_contents(sourcefile);
19 + if (!p) {
20 + return NULL;
21 + }
22 // The filepath without the '.in' extension does not exist on disk. The
23 // sourcefile->diskpath field must be set incase the detector needs to run
24 // 'file -b' on the file.
25 diff --git a/test/detect_files/empty.in b/test/detect_files/empty.in
26 new file mode 100644
27 index 0000000..e69de29
28 diff --git a/test/unit/detector_test.h b/test/unit/detector_test.h
29 index 628b6cc..a26adaa 100644
30 --- a/test/unit/detector_test.h
31 +++ b/test/unit/detector_test.h
32 @@ -36,6 +36,9 @@ void test_detector_disambiguate_m() {
33 ASSERT_DETECT(LANG_OCTAVE, "foo_octave.m");
34 }
35
36 +void test_detector_disambiguate_in() {
37 + ASSERT_NODETECT("empty.in");
38 +}
39 void test_detector_disambiguate_pro() {
40 ASSERT_DETECT(LANG_IDL_PVWAVE, "foo.pro");
41 ASSERT_DETECT(LANG_MAKE, "qmake.pro");
42 @@ -119,6 +122,7 @@ void test_detector_xml_with_custom_extension() {
43 void all_detector_tests() {
44 test_detector_smalltalk();
45 test_detector_disambiguate_m();
46 + test_detector_disambiguate_in();
47 test_detector_disambiguate_pro();
48 test_detector_fortran_fixedfree();
49 test_detector_detect_polyglot();
50 --
51 1.7.0.1
52
+0
-28
debian/patches/rbconfig.patch less more
0 Index: ohcount-3.0.0/build
1 ===================================================================
2 --- ohcount-3.0.0.orig/build
3 +++ ohcount-3.0.0/build
4 @@ -114,12 +114,12 @@ run_test_suite()
5
6 build_ruby_bindings()
7 {
8 - arch=`ruby -rmkmf -e 'print Config::expand(CONFIG["arch"])'`
9 + arch=`ruby -rmkmf -e 'print RbConfig::expand(RbConfig::CONFIG["arch"])'`
10 echo "Generating Ruby bindings for $arch"
11 sh -c "swig -ruby -o ruby/ohcount_wrap.c ruby/ohcount.i" || exit 1
12 mkdir -p ruby/$arch
13 sh -c "$cc $RB_SHARED ruby/ohcount_wrap.c $files -o ruby/$arch/$RB_SHARED_NAME \
14 - -I`ruby -rmkmf -e 'print Config::expand(CONFIG["archdir"])'` \
15 + -I`ruby -rmkmf -e 'print RbConfig::expand(RbConfig::CONFIG["archdir"])'` \
16 -lpcre" || exit 1
17 sh -c "cd test/unit/ruby && ruby ruby_test.rb" || exit 1
18 }
19 @@ -156,7 +156,7 @@ then
20 rm -f src/hash/*.c
21 rm -f src/$SHARED_NAME
22 rm -f ruby/$RB_SHARED_NAME
23 - rm -rf ruby/`ruby -rmkmf -e 'print Config::expand(CONFIG["arch"])'`/*
24 + rm -rf ruby/`ruby -rmkmf -e 'print RbConfig::expand(RbConfig::CONFIG["arch"])'`/*
25 else
26 echo "Usage: build [all|ohcount|shared|tests|ruby|clean]"
27 fi
+0
-5
debian/patches/series less more
0 fix_null_dereference_2.patch
1 fix_null_dereference.patch
2 txx_support.patch
3 disabled_test_suite.patch
4 rbconfig.patch
+0
-12
debian/patches/txx_support.patch less more
0 diff -Naur ohcount-3.0.0/src/hash/extensions.gperf ohcount-3.0.1/src/hash/extensions.gperf
1 --- ohcount-3.0.0/src/hash/extensions.gperf 2009-09-30 17:30:19.000000000 +0000
2 +++ ohcount-3.0.1/src/hash/extensions.gperf 2011-09-26 09:32:34.000000000 +0000
3 @@ -161,6 +161,7 @@
4 tif, BINARY
5 tiff, BINARY
6 tpl, LANG_HTML
7 +txx, LANG_CPP
8 vala, LANG_VALA
9 vb, LANG_VISUALBASIC
10 vba, LANG_VISUALBASIC
11
+0
-27
debian/rules less more
0 #!/usr/bin/make -f
1
2 %:
3 dh $@ --buildsystem=ruby --with ruby
4
5 override_dh_auto_clean:
6 dh_auto_clean -O--buildsystem=ruby
7 ./build clean
8 rm -rf doc_build
9
10 override_dh_install:
11 ./build all
12 dh_install --buildsystem=ruby --with ruby
13 install -d debian/ohcount/usr/lib/ruby/vendor_ruby/ohcount
14 install -d debian/ohcount/usr/bin
15 install -d debian/ohcount-doc/usr/share/doc/ohcount-doc
16 cp bin/ohcount debian/ohcount/usr/bin/
17 cp -R ruby/gestalt ruby/gestalt.rb ruby/ohcount.rb debian/ohcount/usr/lib/ruby/vendor_ruby/ohcount/
18 # build doxygen
19 mkdir doc_build
20 cp -aR doc/* doc_build/
21 (cd doc_build && doxygen Doxyfile)
22 cp -aR doc_build/html/* debian/ohcount-doc/usr/share/doc/ohcount-doc
23 rm -rf debian/ohcount/ruby debian/ohcount-doc/ruby
24
25 get-orig-source:
26 uscan --force-download
+0
-1
debian/source/format less more
0 3.0 (quilt)
+0
-6
debian/watch less more
0 version=4
1 opts="filenamemangle=s%(?:.*?)?v?(\d[\d.]*)\.tar\.gz%ohcount-$1.tar.gz%" \
2 https://github.com/blackducksoftware/ohcount/tags \
3 (?:.*?/)?v?(\d[\d.]*)\.tar\.gz debian uupdate
4
5
00 %%{
11 machine c;
22 write data;
3 include "common.rl";
3 include common "common.rl";
44
55 ...
66 }%%
0 import os, collections
1 from abc import abstractmethod
2 import ohcount
3
4 class _OhcountBase(object):
5
6 def __init__(self, base):
7 self._base = base
8
9 def __getattr__(self, name):
10 if name == '_base':
11 return object.__getattr__(self, name)
12 raise AttributeError
13
14 def __setattr__(self, name, value):
15 if name == '_base':
16 return object.__setattr__(self, name, value)
17 raise AttributeError
18
19 class _OhcountDict(_OhcountBase, collections.Mapping, collections.KeysView):
20
21 def __init__(self, base, mapping):
22 _OhcountBase.__init__(self, base)
23 collections.KeysView.__init__(self, mapping)
24
25 def __getattr__(self, name):
26 if name == '_mapping':
27 return collections.KeysView.__getattr__(self, name)
28 try:
29 return _OhcountBase.__getattr__(self, name)
30 except AttributeError:
31 try:
32 return self.__getitem__(name)
33 except KeyError:
34 raise AttributeError
35 except:
36 raise
37
38 def __setattr__(self, name, value):
39 if name == '_mapping':
40 return collections.KeysView.__setattr__(self, name, value)
41 try:
42 return _OhcountBase.__setattr__(self, name, value)
43 except AttributeError:
44 try:
45 return self.__setitem__(name, value)
46 except KeyError:
47 raise AttributeError
48 except:
49 raise
50
51 def keys(self):
52 return self._mapping
53
54 def __setitem__(self, key, item):
55 raise KeyError
56
57 def __delitem__(self, key):
58 raise KeyError
59
60 def __str__(self):
61 return dict([(key, self[key]) for key in self.keys()]).__str__()
62
63 def iterkeys(self):
64 return iter(self.keys())
65
66 def itervalues(self):
67 for key in self.keys():
68 yield self[key]
69
70 def iteritems(self):
71 for key in self.keys():
72 yield (key, self[key])
73
74 def items(self):
75 return [(key, self[key]) for key in self.keys()]
76
77 def values(self):
78 return [self[key] for key in self.keys()]
79
80 class _OhcountList(_OhcountBase):
81
82 @abstractmethod
83 def _get_value(self, inner):
84 raise NotImplementedError
85
86 def __len__(self):
87 count = 0
88 for e in self:
89 count += 1
90 return count
91
92 def __iter__(self):
93 return self.next()
94
95 def next(self):
96 iter = self._base.head
97 while iter is not None:
98 yield self._get_value(iter)
99 iter = iter.next
100
101 def __str__(self):
102 return [v for v in self].__str__()
103
104 class License(_OhcountDict):
105
106 def __init__(self, base):
107 _OhcountDict.__init__(self, base,
108 ['name','url','nice_name'])
109
110 def __getitem__(self, key):
111 if key == 'name':
112 return self._base.name
113 if key == 'url':
114 return self._base.url
115 if key == 'nice_name':
116 return self._base.nice_name
117 raise KeyError
118
119 class Loc(_OhcountDict):
120
121 def __init__(self, base):
122 _OhcountDict.__init__(self, base,
123 ['lang','code','comments','blanks','filecount','total'])
124
125 def __getitem__(self, key):
126 if key == 'lang' or key == 'language':
127 return self._base.language
128 if key == 'code':
129 return self._base.code
130 if key == 'comments':
131 return self._base.comments
132 if key == 'blanks':
133 return self._base.blanks
134 if key == 'filecount':
135 return self._base.filecount
136 if key == 'total':
137 return self._base.total()
138 raise KeyError
139
140 class LocList(_OhcountDict, _OhcountList):
141
142 def __init__(self, base):
143 _OhcountDict.__init__(self, base,
144 ['code','comments','blanks','filecount','total'])
145
146 def _get_value(self, inner):
147 return Loc(inner.loc)
148
149 def __getitem__(self, key):
150 if key == 'code':
151 return self._base.code()
152 if key == 'comments':
153 return self._base.comments()
154 if key == 'blanks':
155 return self._base.blanks()
156 if key == 'filecount':
157 return self._base.filecount()
158 if key == 'total':
159 return self._base.total()
160 raise KeyError
161
162 def __str__(self):
163 return _OhcountDict.__str__(self)
164
165 def compact(self):
166 return LocList(self._base.compact())
167
168 class SourceFile(_OhcountDict):
169
170 def __init__(self, base):
171 _OhcountDict.__init__(self, base,
172 ['filepath','filename','ext','contents','size','language',
173 'licenses','locs'])
174
175 def _get_licenses(self):
176 result = []
177 list = self._base.get_license_list()
178 if list is not None:
179 iter = list.head
180 while iter is not None:
181 result.append(License(iter.lic))
182 iter = iter.next
183 return result
184
185 def _get_locs(self):
186 return LocList(self._base.get_loc_list())
187
188 def __getitem__(self, key):
189 if key == 'filepath':
190 return self._base.filepath
191 if key == 'filename':
192 return self._base.filename
193 if key == 'ext':
194 return self._base.ext
195 if key == 'contents':
196 return self._base.get_contents()
197 if key == 'size':
198 return self._base.contents_size()
199 if key == 'language':
200 return self._base.get_language()
201 if key == 'licenses':
202 return self._get_licenses()
203 if key == 'locs':
204 return self._get_locs()
205 raise AttributeError
206
207 def annotate(self):
208 return self._base.annotate()
209
210 def raw_entities(self):
211 return self._base.raw_entities()
212
213 class SourceFileList(_OhcountList):
214
215 def __init__(self, **kwargs):
216 _OhcountList.__init__(self, ohcount.SourceFileList(kwargs))
217
218 def _get_value(self, inner):
219 return SourceFile(inner.sf)
220
221 def analyze_languages(self):
222 return LocList( self._base.analyze_languages() )
223
224 def add_directory(self, path):
225 if not os.path.isdir(path):
226 raise SyntaxError('Input path is not a directory: %s' % path)
227 self._base.add_directory(path)
228
229 def add_file(self, filepath):
230 if not os.path.isfile(filepath):
231 raise SyntaxError('Input path is not a file: %s' % filepath)
232 self._base.add_file(filepath)
233
0 #=== mingw_setup.py by Phillip J. Eby
1 """Create pythonNN.def and libpythonNN.a in 'PythonNN/libs' directory
2
3 This script makes it possible to use the MinGW compiler tools to
4 build C extensions that work with the standard Windows Python
5 distribution.
6
7 Before running, you should have installed the MinGW compiler toolset,
8 and placed its 'bin' directory on your PATH. An easy way to do this
9 is to install Cygwin's "binutils", "gcc", and "mingw-*" packages,
10 then run this script from the Cygwin shell. (Be sure to use *Windows*
11 Python, not Cygwin python!)
12
13 Once this script has been run, you should be able to build extensions
14 using distutils in the standard way, as long as you select the
15 'mingw32' compiler, and the required tools are on your PATH. See
16 the "Installing Python Modules" manual for more information on
17 selecting a compiler.
18 """
19
20
21 from distutils.spawn import find_executable
22 from distutils.sysconfig import get_config_var
23 from distutils import __file__ as distutils_file
24 import os, re, sys
25
26 if sys.platform=='cygwin':
27 print "Please run this script using Windows python,",
28 print "not Cygwin python. E.g, try:"
29 print
30 print "/cygdrive/c/PythonNN/python", " ".join(sys.argv)
31 print
32 print "(where NN is the major/minor python version number)"
33 sys.exit()
34
35 basename = 'python%d%d' % sys.version_info[:2]
36
37 libs_dir = os.path.join(get_config_var('prefix'),'libs')
38 lib_file = os.path.join(libs_dir,basename+'.lib')
39 def_file = os.path.join(libs_dir,basename+'.def')
40 ming_lib = os.path.join(libs_dir,'lib%s.a' % basename)
41
42 distutils_cfg = os.path.join(os.path.dirname(distutils_file),'distutils.cfg')
43
44 export_match = re.compile(r"^_imp__(.*) in python\d+\.dll").match
45
46 nm = find_executable('nm')
47 dlltool = find_executable('dlltool')
48
49 if not nm or not dlltool:
50 print "'nm' and/or 'dlltool' were not found;"
51 print "Please make sure they're on your PATH."
52 sys.exit()
53
54 nm_command = '%s -Cs %s' % (nm, lib_file)
55
56 print "Building", def_file, "using", nm_command
57 f = open(def_file,'w')
58 print >>f, "LIBRARY %s.dll" % basename
59 print >>f, "EXPORTS"
60
61
62 nm_pipe = os.popen(nm_command)
63 for line in nm_pipe.readlines():
64 m = export_match(line)
65 if m:
66 print >>f, m.group(1)
67 f.close()
68
69 exit = nm_pipe.close()
70 if exit:
71 print "nm exited with status", exit
72 print "Please check that", lib_file, "exists and is valid."
73 sys.exit()
74
75
76 print "Building",ming_lib,"using",dlltool
77 dlltool_pipe = os.popen(
78 "%s --dllname %s.dll --def %s --output-lib %s" %
79 (dlltool, basename, def_file, ming_lib)
80 )
81
82 dlltool_pipe.readlines()
83 exit = dlltool_pipe.close()
84 if exit:
85 print "dlltool exited with status", exit
86 print "Unable to proceed."
87 sys.exit()
88
89 print
90 print "Installation complete. You may wish to add the following"
91 print "lines to", distutils_cfg, ':'
92 print
93 print "[build]"
94 print "compiler = mingw32"
95 print
96 print "This will make the distutils use MinGW as the default"
97 print "compiler, so that you don't need to configure this for"
98 print "every 'setup.py' you run."
99
0 #!/usr/bin/env python
1
2 import distutils.ccompiler
3 from distutils.core import setup, Extension
4 from distutils.command.build import build
5 from distutils.command.build_ext import build_ext
6 from distutils.command.install_lib import install_lib
7 import os, sys
8 from glob import glob
9
10 if not hasattr(sys, 'version_info') or sys.version_info < (2,6,0,'final'):
11 raise SystemExit("Ohcount requires Python 2.6 or later.")
12
13 class build_ohcount(build):
14 """Ohcount already have a script named 'build', from the original package,
15 so it conflicts with Python default build path. To solve this, setup.py
16 will use the directory 'build-python' instead. The original distutils
17 execute 'build_py' before 'build_ext', but we need the wrapper ohcount.py
18 created by SWIG to be installed too, so we need to invert this order.
19 """
20
21 sub_commands = [('build_ext', build.has_ext_modules), # changed
22 ('build_py', build.has_pure_modules), # changed
23 ('build_clib', build.has_c_libraries),
24 ('build_scripts', build.has_scripts),
25 ]
26
27 def initialize_options(self):
28 build.initialize_options(self)
29 self.build_base = 'build-python'
30
31 def newer_than(srclist, dstlist):
32 for left, right in zip(srclist, dstlist):
33 if not os.path.exists(right):
34 return True
35 left_stat = os.lstat(left)
36 right_stat = os.lstat(right)
37 if left_stat.st_mtime > right_stat.st_mtime:
38 return True
39 return False
40
41 class build_ohcount_ext(build_ext):
42 """This class implements extra steps needed by Ohcount build process."""
43
44 def run(self):
45 parsers = glob('src/parsers/*.rl')
46 parsers_h = [f.replace('.rl', '.h') for f in parsers]
47 if newer_than(parsers, parsers_h):
48 os.system('cd src/parsers/ && bash ./compile')
49 hash_files = glob('src/hash/*.gperf')
50 hash_srcs = []
51 for f in hash_files:
52 if not f.endswith('languages.gperf'):
53 hash_srcs.append(f.replace('s.gperf', '_hash.h'))
54 else:
55 hash_srcs.append(f.replace('s.gperf', '_hash.c'))
56 if newer_than(hash_files, hash_srcs):
57 os.system('cd src/hash/ && bash ./generate_headers')
58 return build_ext.run(self)
59
60 # Overwrite default Mingw32 compiler
61 (module_name, class_name, long_description) = \
62 distutils.ccompiler.compiler_class['mingw32']
63 module_name = "distutils." + module_name
64 __import__(module_name)
65 module = sys.modules[module_name]
66 Mingw32CCompiler = vars(module)[class_name]
67
68 class Mingw32CCompiler_ohcount(Mingw32CCompiler):
69 """Ohcount CCompiler version for Mingw32. There is a problem linking
70 against msvcrXX for Python 2.6.4: as both DLLs msvcr and msvcr90 are
71 loaded, it seems to happen some unexpected segmentation faults in
72 several function calls."""
73
74 def __init__(self, *args, **kwargs):
75 Mingw32CCompiler.__init__(self, *args, **kwargs)
76 self.dll_libraries=[] # empty link libraries list
77
78 _new_compiler = distutils.ccompiler.new_compiler
79
80 def ohcount_new_compiler(plat=None,compiler=None,verbose=0,dry_run=0,force=0):
81 if compiler == 'mingw32':
82 inst = Mingw32CCompiler_ohcount(None, dry_run, force)
83 else:
84 inst = _new_compiler(plat,compiler,verbose,dry_run,force)
85 return inst
86
87 distutils.ccompiler.new_compiler = ohcount_new_compiler
88
89 # Ohcount python extension
90 ext_modules=[
91 Extension(
92 name='ohcount._ohcount',
93 sources= [
94 'ruby/ohcount.i',
95 'src/sourcefile.c',
96 'src/detector.c',
97 'src/licenses.c',
98 'src/parser.c',
99 'src/loc.c',
100 'src/log.c',
101 'src/diff.c',
102 'src/parsed_language.c',
103 'src/hash/language_hash.c',
104 ],
105 libraries=['pcre'],
106 swig_opts=['-outdir', './python/'],
107 )
108 ]
109
110 setup(
111 name='ohcount',
112 version = '3.0.0',
113 description = 'Ohcount is the source code line counter that powers Ohloh.',
114 long_description =
115 'Ohcount supports over 70 popular programming languages, and has been '
116 'used to count over 6 billion lines of code by 300,000 developers! '
117 'Ohcount does more more than just count lines of code. It can also '
118 'detect popular open source licenses such as GPL within a large '
119 'directory of source code. It can also detect code that targets a '
120 'particular programming API, such as Win32 or KDE.',
121 author = 'Mitchell Foral',
122 author_email = 'mitchell@caladbolg.net',
123 license = 'GNU GPL',
124 platforms = ['Linux','Mac OSX'],
125 keywords = ['ohcount','ohloh','loc','source','code','line','counter'],
126 url = 'http://www.ohloh.net/p/ohcount',
127 download_url = 'http://sourceforge.net/projects/ohcount/files/',
128 packages = ['ohcount'],
129 package_dir = {'ohcount': 'python'},
130 classifiers = [
131 'Development Status :: 5 - Production/Stable',
132 'License :: OSI Approved :: GNU General Public License (GPL)'
133 'Intended Audience :: Developers',
134 'Natural Language :: English',
135 'Programming Language :: C',
136 'Programming Language :: Python',
137 'Topic :: Software Development :: Libraries :: Python Modules',
138 ],
139 ext_modules=ext_modules,
140 cmdclass={
141 'build': build_ohcount,
142 'build_ext': build_ohcount_ext,
143 },
144 )
145
1212 require 'gestalt/rules/gestalt_rule'
1313 require 'gestalt/rules/java_import_rule'
1414 require 'gestalt/rules/csharp_using_rule'
15 require 'gestalt/rules/find_java_imports_rule'
1615 require 'gestalt/rules/maven_parser'
1716 require 'gestalt/rules/maven_rule'
1817 require 'gestalt/rules/csproj_parser'
11 module Gestalt
22
33 define_platform 'dot_net' do
4 language :csharp, :min_percent => 10
4 _or do
5 language :csharp, :min_percent => 10
6 gestalt :platform, 'asp_net'
7 gestalt :platform, 'wpf'
8 gestalt :platform, 'silverlight'
9 end
510 end
611
712 define_platform 'asp_net' do
813 filenames('\.(aspx|ascx|ashx|asax|axd)$')
914 end
10
11 define_platform 'nunit' do
12 _and do
13 gestalt(:platform, 'dot_net')
14 csharp_using /^NUnit\b/
15 end
16 end
17
18 define_platform 'nhibernate' do
19 _and do
20 gestalt(:platform, 'dot_net')
21 csharp_using /^NHibernate\b/
22 end
23 end
24
25 # BizTalk
26 define_platform 'dot_net_biztalk' do
27 _and do
28 gestalt(:platform, 'dot_net')
29 _or do
30 csharp_using /^Microsoft\.Solutions\b/
31 csharp_using /^Microsoft\.BizTalk\b/
32 end
33 end
34 end
35
36 # Connected Services Framework
37 define_platform 'dot_net_csf' do
38 _and do
39 gestalt(:platform, 'dot_net')
40 csharp_using /^Microsoft\.Csf\b/
41 end
42 end
43
44 # Microsoft Content Management Server
45 define_platform 'dot_net_cms' do
46 _and do
47 gestalt(:platform, 'dot_net')
48 csharp_using /^Microsoft\.ContentManagement\b/
49 end
50 end
51
52 # Exchange
53 define_platform 'dot_net_exchange' do
54 _and do
55 gestalt(:platform, 'dot_net')
56 csharp_using /^Microsoft\.Exchange\b/
57 end
58 end
59
60 # Microsoft Operations Manager (Mom)
61 define_platform 'dot_net_mom' do
62 _and do
63 gestalt(:platform, 'dot_net')
64 csharp_using /^Microsoft\.EnterpriseManagement\.Mom\b/
65 end
66 end
67
68 # A general category of software.
69 # Not a particular technology, but it "smells" like middle-tier/enterprise software.
70 define_platform 'dot_net_enterprise' do
71 _and do
72 gestalt(:platform, 'dot_net')
73 _or do
74 gestalt(:platform, 'dot_net_biztalk')
75 gestalt(:platform, 'dot_net_exchange')
76 gestalt(:platform, 'dot_net_cms')
77 gestalt(:platform, 'dot_net_csf')
78 gestalt(:platform, 'dot_net_mom')
79 csharp_using /^System\.Runtime\.Remoting\b/
80 csharp_using /^System\.DirectoryServices\b/
81 csharp_using /^System\.ServiceModel\b/
82 csharp_using /^System\.(Data\.)?Linq\b/
83 csharp_using /^System\.Data\b/
84 end
85 end
86 end
8715
8816 define_platform 'wpf' do
8917 filenames '\.xaml$'
2828 define_platform 'jasper_reports_java' do
2929 _or do
3030 maven_dependency /jasperreports/
31 java_keywords '\bnet\.sf\.jasperreports\b'
31 java_keywords '\bnet\.sf\.jasperreports\b'
3232 end
3333 end
3434
00 module Ohcount
11 module Gestalt
2
3 define_java_jar do
4 find_filenames /([^\\^\/]*\.jar)/i, :name_from_match => 1
5 end
6
7 define_java_import do
8 find_java_imports
9 end
102
113 # Java Application Servers
124
1010 end
1111
1212 def process_source_file(source_file)
13 @count += 1 if regex.match(source_file.filename)
13 @count += 1 if regex.match(source_file.filepath)
1414 end
1515
1616 def regex
+0
-54
ruby/gestalt/rules/find_java_imports_rule.rb less more
0 module Ohcount
1 module Gestalt
2
3 # Will yield one trigger per java import - each with the name of the imported
4 # namespace. Example java source file:
5 #
6 # import com.foo.bar;
7 #
8 # will yield a trigger with name='com.foo.bar'
9 class FindJavaImportsRule < FileRule
10 attr_reader :keywords, :language
11
12 def initialize(*args)
13 @trigger_hash = {}
14 super(*args)
15 end
16
17 def process_source_file(source_file)
18 return unless source_file.language_breakdown('java')
19
20 java_code = source_file.language_breakdown('java').code
21 java_code.scan(import_regexp).each do |matches|
22 name = matches[0]
23 @trigger_hash[name] = @trigger_hash[name].to_i + 1
24 end
25 end
26
27 # implement deep clone
28 def clone
29 self.class.new(:min => @min_count)
30 end
31
32 def triggers(gestalt_engine)
33 triggers = []
34 @trigger_hash.each do |k,v|
35 triggers << Trigger.new(:name => FindJavaImportsRule.truncate_name(k, 3), :count => v)
36 end
37 triggers
38 end
39
40 def import_regexp
41 /^\s*import\s+([a-zA-Z][\w\.\*\-]*)\b/
42 end
43
44 # Truncates the java import namespace to a maximum depth.
45 # For instance,
46 # truncate_name("com.sun.identity.authentication", 3) => "com.sun.identity"
47 def self.truncate_name(s, max_depth)
48 s.to_s.split('.')[0, max_depth].join('.')
49 end
50
51 end
52 end
53 end
8484 new_rule FindFilenamesRule, *args
8585 end
8686
87 def find_java_imports(*args)
88 new_rule FindJavaImportsRule, *args
89 end
90
9187 def method_missing(m,*args, &block)
9288 if m.to_s =~ /^(.*)_keywords$/
9389 language = $1
77
88 %include typemaps.i
99
10 #if defined(SWIGRUBY)
11
1012 %typemap(in) (register const char *str, register unsigned int len) {
1113 Check_Type($input, T_STRING);
12 $1 = STR2CSTR($input);
13 $2 = RSTRING($input)->len;
14 $1 = StringValuePtr($input);
15 $2 = RSTRING_LEN($input);
1416 };
1517
1618 %typemap(out) char ** {
2123 $result = arr;
2224 };
2325
26 #elif defined(SWIGPYTHON)
27
28 %typemap(in) (register const char *str, register unsigned int len) {
29 if (!PyString_Check($input)) {
30 PyErr_SetString(PyExc_SyntaxError, "Invalid parameter");
31 return NULL;
32 }
33 $1 = PyString_AsString($input);
34 $2 = PyString_Size($input);
35 };
36
37 %typemap(out) char ** {
38 int i;
39 PyObject *arr = PyList_New(0);
40 for (i = 0; $1[i] != NULL; i++)
41 PyList_Append(arr, PyString_FromString($1[i]));
42 $result = arr;
43 };
44
45
46 #else
47 #error "You should define specific translation rules for this language."
48 #endif
49
2450 %nodefaultctor SourceFile;
2551 %immutable;
2652 %include "../src/languages.h"
2753 %include "../src/structs.h"
2854 %mutable;
2955
56 %extend Loc {
57 int total() {
58 return ohcount_loc_total(self);
59 }
60 }
61
62 %extend LocListItem {
63 int code() {
64 return ohcount_loc_list_code(self);
65 }
66 int comments() {
67 return ohcount_loc_list_comments(self);
68 }
69 int blanks() {
70 return ohcount_loc_list_blanks(self);
71 }
72 int total() {
73 return ohcount_loc_list_total(self);
74 }
75 int filecount() {
76 return ohcount_loc_list_filecount(self);
77 }
78 }
79
3080 %extend SourceFile {
3181 void set_diskpath(const char *diskpath) {
3282 ohcount_sourcefile_set_diskpath(self, diskpath);
58108 LocDeltaList *_diff(SourceFile *to) {
59109 return ohcount_sourcefile_diff(self, to);
60110 }
111 #if defined(SWIGRUBY)
61112 void set_filenames(VALUE filenames) {
62 int i, length = RARRAY(filenames)->len;
113 int i, length = RARRAY_LEN(filenames);
63114 char **fnames = calloc(length + 1, sizeof(char *));
64 VALUE *iter = RARRAY(filenames)->ptr;
115 VALUE *iter = RARRAY_PTR(filenames);
65116 for (i = 0; i < length; i++, iter++)
66 fnames[i] = STR2CSTR(*iter);
67 ohcount_sourcefile_set_filenames(self, fnames);
68 free(fnames);
117 fnames[i] = StringValuePtr(*iter);
118 self->filenames = fnames;
69119 }
70120 SourceFile(const char *filepath, VALUE opt_hash=NULL) {
71121 SourceFile *sourcefile = ohcount_sourcefile_new(filepath);
73123 VALUE val;
74124 val = rb_hash_aref(opt_hash, ID2SYM(rb_intern("contents")));
75125 if (val && rb_type(val) == T_STRING)
76 ohcount_sourcefile_set_contents(sourcefile, STR2CSTR(val));
126 ohcount_sourcefile_set_contents(sourcefile, StringValuePtr(val));
77127 val = rb_hash_aref(opt_hash, ID2SYM(rb_intern("file_location")));
78128 if (val && rb_type(val) == T_STRING)
79 ohcount_sourcefile_set_diskpath(sourcefile, STR2CSTR(val));
129 ohcount_sourcefile_set_diskpath(sourcefile, StringValuePtr(val));
80130 val = rb_hash_aref(opt_hash, ID2SYM(rb_intern("filenames")));
81131 if (val && rb_type(val) == T_ARRAY)
82132 SourceFile_set_filenames(sourcefile, val);
83133 }
84134 return sourcefile;
85135 }
136 #elif defined(SWIGPYTHON)
137 void set_filenames(PyObject *filenames) {
138 int i, length;
139 char **fnames;
140 if (!PyList_Check(filenames)) {
141 PyErr_SetString(PyExc_SyntaxError, "Invalid parameter, expected a list of strings");
142 return;
143 }
144 length = PyList_Size(filenames);
145 fnames = calloc(length + 1, sizeof(char *));
146 for (i = 0; i < length; i++) {
147 PyObject *s = PyList_GetItem(filenames, i);
148 if (!PyString_Check(s)) {
149 PyErr_SetString(PyExc_SyntaxError, "Invalid parameter, expected a list of strings");
150 return;
151 }
152 fnames[i] = PyString_AsString(s);
153 }
154 ohcount_sourcefile_set_filenames(self, fnames);
155 free(fnames);
156 }
157 static void py_annotate_callback(const char *language, const char *entity,
158 int start, int end, void *userdata) {
159 PyObject *list = (PyObject *) userdata;
160 PyObject *dict = PyDict_New();
161 PyDict_SetItem(dict, PyString_FromString("language"),
162 PyString_FromString(language));
163 PyDict_SetItem(dict, PyString_FromString("entity"),
164 PyString_FromString(entity));
165 PyDict_SetItem(dict, PyString_FromString("start"),
166 PyInt_FromLong(start));
167 PyDict_SetItem(dict, PyString_FromString("end"),
168 PyInt_FromLong(end));
169 PyList_Append(list, dict);
170 }
171 PyObject *annotate() {
172 PyObject *list = PyList_New(0);
173 ohcount_sourcefile_parse_with_callback(self, SourceFile_py_annotate_callback, list);
174 return list;
175 }
176 PyObject *raw_entities() {
177 PyObject *list = PyList_New(0);
178 ohcount_sourcefile_parse_entities_with_callback(self, SourceFile_py_annotate_callback, list);
179 return list;
180 }
181 SourceFile(const char *filepath, PyObject *args) {
182 SourceFile *sourcefile = ohcount_sourcefile_new(filepath);
183 if (args) {
184 PyObject *val;
185 if (!PyDict_Check(args)) {
186 PyErr_SetString(PyExc_SyntaxError, "Invalid argument");
187 ohcount_sourcefile_free(sourcefile);
188 return NULL;
189 }
190 val = PyDict_GetItem(args, PyString_FromString("contents"));
191 if (val && PyString_Check(val))
192 ohcount_sourcefile_set_contents(sourcefile, PyString_AsString(val));
193 val = PyDict_GetItem(args, PyString_FromString("file_location"));
194 if (val && PyString_Check(val))
195 ohcount_sourcefile_set_diskpath(sourcefile, PyString_AsString(val));
196 val = PyDict_GetItem(args, PyString_FromString("filenames"));
197 if (val && PyString_Check(val))
198 SourceFile_set_filenames(sourcefile, val);
199 }
200 return sourcefile;
201 }
202
203 #endif
86204 ~SourceFile() {
205 if (self->filenames)
206 free(self->filenames);
87207 ohcount_sourcefile_free(self);
88208 }
89209 };
90210
91 %extend SourceFileList {
211 %extend SourceFileListItem {
212 #if defined(SWIGRUBY)
213
92214 static VALUE rb_add_directory(VALUE directory, SourceFileList *list) {
93215 if (directory && rb_type(directory) == T_STRING)
94 ohcount_sourcefile_list_add_directory(list, STR2CSTR(directory));
216 ohcount_sourcefile_list_add_directory(list, StringValuePtr(directory));
95217 return Qnil;
96218 }
97 SourceFileList(VALUE opt_hash=NULL) {
219 static VALUE rb_add_file(VALUE file, SourceFileList *list) {
220 if (file && rb_type(file) == T_STRING)
221 ohcount_sourcefile_list_add_file(list, StringValuePtr(file));
222 return Qnil;
223 }
224 SourceFileListItem(VALUE opt_hash=NULL) {
98225 SourceFileList *list = ohcount_sourcefile_list_new();
99226 if (opt_hash) {
100227 VALUE val;
101228 val = rb_hash_aref(opt_hash, ID2SYM(rb_intern("paths")));
102229 if (val && rb_type(val) == T_ARRAY)
103 rb_iterate(rb_each, val, SourceFileList_rb_add_directory, (VALUE)list);
104 }
105 return list;
106 }
107 ~SourceFileList() {
230 rb_iterate(rb_each, val, SourceFileListItem_rb_add_directory, (VALUE)list);
231 val = rb_hash_aref(opt_hash, ID2SYM(rb_intern("files")));
232 if (val && rb_type(val) == T_ARRAY)
233 rb_iterate(rb_each, val, SourceFileListItem_rb_add_file, (VALUE)list);
234 }
235 return list;
236 }
237
238 #elif defined(SWIGPYTHON)
239
240 SourceFileListItem(PyObject *args) {
241 SourceFileList *list = ohcount_sourcefile_list_new();
242 if (args) {
243 PyObject *val;
244 if (!PyDict_Check(args)) {
245 PyErr_SetString(PyExc_SyntaxError, "Invalid argument");
246 ohcount_sourcefile_list_free(list);
247 return NULL;
248 }
249 val = PyDict_GetItem(args, PyString_FromString("paths"));
250 if (val && PyList_Check(val)) {
251 int i, length = PyList_Size(val);
252 for (i = 0; i < length; i++) {
253 PyObject *s = PyList_GetItem(val, i);
254 if (!PyString_Check(s)) {
255 PyErr_SetString(PyExc_SyntaxError, "Invalid 'paths', expected a list of strings");
256 ohcount_sourcefile_list_free(list);
257 return NULL;
258 }
259 ohcount_sourcefile_list_add_directory(list, PyString_AsString(s));
260 }
261 }
262 val = PyDict_GetItem(args, PyString_FromString("files"));
263 if (val && PyList_Check(val)) {
264 int i, length = PyList_Size(val);
265 for (i = 0; i < length; i++) {
266 PyObject *s = PyList_GetItem(val, i);
267 if (!PyString_Check(s)) {
268 PyErr_SetString(PyExc_SyntaxError, "Invalid 'files', expected a list of strings");
269 ohcount_sourcefile_list_free(list);
270 return NULL;
271 }
272 ohcount_sourcefile_list_add_file(list, PyString_AsString(s));
273 }
274 }
275 }
276 return list;
277 }
278
279 #endif
280
281 ~SourceFileListItem() {
108282 ohcount_sourcefile_list_free(self);
109283 }
110284 void add_file(const char *filepath) {
22 # Ohcount module tweaked for use by Ohloh.
33
44 $: << File.expand_path(File.dirname(__FILE__))
5 $: << "#{File.expand_path(File.dirname(__FILE__))}/#{`#{File.dirname(__FILE__)}/print_arch`.strip}"
56
6 begin
7 require 'ohcount.so'
8 rescue LoadError
9 require 'rbconfig'
10 include Config
11 require "#{Config::CONFIG['arch']}/ohcount.so"
12 end
7 require 'ohcount.so'
138
149 module Ohcount
1510 class SourceFile
1611 def file_location=(value) set_diskpath(value) end
1712 def file_location() diskpath() end
1813 def filenames=(value) set_filenames(value) end
19 def contents() get_contents() end
2014 def polyglot() get_language() end
15
16 def contents
17 data = get_contents()
18 data.force_encoding(Encoding.default_external)
19 end
2120
2221 def language_breakdowns
2322 list = get_parsed_language_list()
0 #!/usr/bin/env ruby
1 require 'mkmf'
2
3 arch = RbConfig::expand(CONFIG["arch"])
4
5 distro = if File.exist?("/etc/issue")
6 # this is "", "CentOS" or "Ubuntu"
7 `cat /etc/issue`.split.first.downcase
8 end
9
10 unless ["centos", nil, "ubuntu"].include? distro
11 STDERR.puts "unhandled /etc/issue result: #{distro}"
12 end
13
14 # either <arch> or <arch>_<distro> if distro is non-null
15 puts [arch, distro].compact.join("_")
11 // See COPYING for license information.
22
33 #include <ctype.h>
4 #include <magic.h>
45 #include <stdio.h>
56 #include <stdlib.h>
67 #include <string.h>
1920 #define ISAMBIGUOUS(x) (x[0] == '\2')
2021 #define DISAMBIGUATEWHAT(x) &x[1]
2122
23 #ifdef _WIN32
24 # include <fcntl.h>
25 # define mkstemp(p) _open(_mktemp(p), _O_CREAT | _O_SHORT_LIVED | _O_EXCL)
26 #endif
27
28 /* Parse the output of libmagic and return a language, if any.
29 * The contents of string `line` will be destroyed.
30 */
31 const char *magic_parse(char *line) {
32 char *p, *pe;
33 char *eol = line + strlen(line);
34
35 char buf[80];
36 size_t length;
37
38 for (p = line; p < eol; p++) *p = tolower(*p);
39 p = strstr(line, "script text"); // Example: "script text executable for perl -w,"
40 if (p && p == line) {
41 p = strstr(line, "for ");
42 if (p) {
43 p += 4;
44 pe = p;
45 while (isalnum(*pe)) pe++;
46 length = pe - p;
47 strncpy(buf, p, length);
48 buf[length] = '\0';
49 struct LanguageMap *rl = ohcount_hash_language_from_name(buf, length);
50 if (rl) return(rl->name);
51 }
52 }
53
54 p = strstr(line, "script"); // Example: "PHP script, ASCII text"
55 if (p) {
56 do {
57 p--;
58 pe = p;
59 while (*p == ' ') p--;
60 while (p != line && isalnum(*(p - 1))) p--;
61 if (p != line && *(p - 1) == '-') p--;
62 } while (*p == '-'); // Skip over any switches.
63 length = pe - p;
64 strncpy(buf, p, length);
65 buf[length] = '\0';
66 struct LanguageMap *rl = ohcount_hash_language_from_name(buf, length);
67 if (rl) return(rl->name);
68 } else if (strstr(line, "xml")) return(LANG_XML);
69
70 return NULL;
71 }
72
73 /* Use libmagic to detect file language
74 */
75 const char *detect_language_magic(SourceFile *sourcefile) {
76 char line[80];
77
78 magic_t cookie = magic_open(MAGIC_NONE);
79 if (cookie == NULL) {
80 fprintf(stderr, "libmagic: %s\n", magic_error(cookie));
81 exit(1);
82 }
83 if (magic_load(cookie, NULL) != 0) {
84 fprintf(stderr, "libmagic: %s\n", magic_error(cookie));
85 magic_close(cookie);
86 exit(1);
87 }
88
89 if (sourcefile->diskpath) {
90 const char *magic = magic_file(cookie, sourcefile->diskpath);
91 if (magic == NULL) {
92 fprintf(stderr, "libmagic: %s\n", magic_error(cookie));
93 magic_close(cookie);
94 exit(1);
95 }
96 strncpy(line, magic, sizeof(line));
97 line[sizeof(line)-1] = '\0';
98 } else {
99 char *p = ohcount_sourcefile_get_contents(sourcefile);
100 if (!p) return NULL;
101
102 const char *magic = magic_buffer(cookie, p, strlen(p));
103 if (magic == NULL) {
104 fprintf(stderr, "libmagic: %s\n", magic_error(cookie));
105 magic_close(cookie);
106 exit(1);
107 }
108 strncpy(line, magic, sizeof(line));
109 line[sizeof(line)-1] = '\0';
110 }
111
112 magic_close(cookie);
113
114 return magic_parse(line);
115 }
116
117 /* Use all available means to detect file language
118 */
22119 const char *ohcount_detect_language(SourceFile *sourcefile) {
23120 const char *language = NULL;
24121 char *p, *pe;
27124 // Attempt to detect based on file extension.
28125 length = strlen(sourcefile->ext);
29126 struct ExtensionMap *re = ohcount_hash_language_from_ext(sourcefile->ext,
30 length);
127 length);
31128 if (re) language = re->value;
32 if (language == NULL) {
129 if (!language) {
33130 // Try the lower-case version of this extension.
34131 char lowerext[length + 1];
35132 strncpy(lowerext, sourcefile->ext, length);
36133 lowerext[length] = '\0';
37134 for (p = lowerext; p < lowerext + length; p++) *p = tolower(*p);
38135 struct ExtensionMap *re = ohcount_hash_language_from_ext(lowerext, length);
39 if (re) return re->value;
40 }
136 if (re) language = re->value;
137 }
138
139 // Attempt to detect using Emacs mode line (/^-\*-\s*mode[\s:]*\w/i).
140 if(!language) {
141 char line[81] = { '\0' }, buf[81];
142 p = ohcount_sourcefile_get_contents(sourcefile);
143 pe = p;
144 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
145 while (pe < eof) {
146 // Get the contents of the first line.
147 while (pe < eof && *pe != '\r' && *pe != '\n') pe++;
148 length = (pe - p <= sizeof(line)) ? pe - p : sizeof(line);
149 strncpy(line, p, length);
150 line[length] = '\0';
151 if (*line == '#' && *(line + 1) == '!') {
152 // First line was sh-bang; loop to get contents of second line.
153 while (*pe == '\r' || *pe == '\n') pe++;
154 p = pe;
155 } else break;
156 }
157 p = strstr(line, "-*-");
158 if (p) {
159 p += 3;
160 while (*p == ' ' || *p == '\t') p++;
161 // detect "mode" (any capitalization)
162 if (strncasecmp(p, "mode", 4) == 0) {
163 p += 4;
164 while (*p == ' ' || *p == '\t' || *p == ':') p++;
165 }
166 pe = p;
167 while (!isspace(*pe) && *pe != ';' && pe != strstr(pe, "-*-")) pe++;
168 length = (pe - p <= sizeof(buf)) ? pe - p : sizeof(buf);
169 strncpy(buf, p, length);
170 buf[length] = '\0';
171
172 // Special case for "c" or "C" emacs mode header: always means C, not C++
173 if (strcasecmp(buf, "c") == 0) {
174 return LANG_C;
175 }
176
177 // First try it with the language name.
178 struct LanguageMap *rl = ohcount_hash_language_from_name(buf, length);
179 if (rl) language = rl->name;
180 if(!language) {
181 // Then try it with the extension table.
182 struct ExtensionMap *re = ohcount_hash_language_from_ext(buf, length);
183 if (re) language = re->value;
184 }
185 if (!language) {
186 // Try the lower-case version of this modeline.
187 for (pe = buf; pe < buf+length; pe++) *pe = tolower(*pe);
188 // First try it with the language name.
189 rl = ohcount_hash_language_from_name(buf, length);
190 if (rl) language = rl->name;
191 }
192 if (!language) {
193 // Then try it with the extension table.
194 struct ExtensionMap *re = ohcount_hash_language_from_ext(buf, length);
195 if (re) language = re->value;
196 }
197 }
198 }
199
200 // Attempt to detect based on filename.
201 if(!language) {
202 length = strlen(sourcefile->filename);
203 struct FilenameMap *rf =
204 ohcount_hash_language_from_filename(sourcefile->filename, length);
205 if (rf) language = rf->value;
206 }
207
208 // Attempt to detect based on Unix 'file' command.
209 if(!language) {
210 language = detect_language_magic(sourcefile);
211 }
212
41213 if (language) {
42214 if (ISAMBIGUOUS(language)) {
43215 // Call the appropriate function for disambiguation.
45217 struct DisambiguateFuncsMap *rd =
46218 ohcount_hash_disambiguate_func_from_id(DISAMBIGUATEWHAT(language),
47219 length);
48 if (rd) return rd->value(sourcefile);
49 } else return ISBINARY(language) ? NULL : language;
50 }
51
52 // Attempt to detect based on filename.
53 length = strlen(sourcefile->filename);
54 struct FilenameMap *rf =
55 ohcount_hash_language_from_filename(sourcefile->filename, length);
56 if (rf) return rf->value;
57
58 char line[81] = { '\0' }, buf[81];
59
60 // Attempt to detect using Emacs mode line (/^-\*-\s*mode[\s:]*\w/i).
61 p = ohcount_sourcefile_get_contents(sourcefile);
62 pe = p;
63 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
64 while (pe < eof) {
65 // Get the contents of the first line.
66 while (pe < eof && *pe != '\r' && *pe != '\n') pe++;
67 length = (pe - p <= sizeof(line)) ? pe - p : sizeof(line);
68 strncpy(line, p, length);
69 line[length] = '\0';
70 if (*line == '#' && *(line + 1) == '!') {
71 // First line was sh-bang; loop to get contents of second line.
72 while (*pe == '\r' || *pe == '\n') pe++;
73 p = pe;
74 } else break;
75 }
76 char *eol = line + strlen(line);
77 for (p = line; p < eol; p++) *p = tolower(*p);
78 p = strstr(line, "-*-");
79 if (p) {
80 p += 3;
81 while (*p == ' ' || *p == '\t') p++;
82 if (strncmp(p, "mode", 4) == 0) {
83 p += 4;
84 while (*p == ' ' || *p == '\t' || *p == ':') p++;
85 }
86 pe = p;
87 while (isalnum(*pe)) pe++;
88 length = pe - p;
89 strncpy(buf, p, length);
90 buf[length] = '\0';
91 struct LanguageMap *rl = ohcount_hash_language_from_name(buf, length);
92 if (rl) return rl->name;
93 }
94
95 // Attempt to detect based on Unix 'file' command.
96 int tmpfile = 0;
97 char *path = sourcefile->filepath;
98 if (sourcefile->diskpath)
99 path = sourcefile->diskpath;
100 if (access(path, F_OK) != 0) { // create temporary file
101 path = malloc(21);
102 strncpy(path, "/tmp/ohcount_XXXXXXX", 20);
103 *(path + 21) = '\0';
104 int fd = mkstemp(path);
105 char *contents = ohcount_sourcefile_get_contents(sourcefile);
106 log_it("contents:");
107 log_it(contents);
108 length = contents ? strlen(contents) : 0;
109 write(fd, contents, length);
110 close(fd);
111 tmpfile = 1;
112 }
113 char command[strlen(path) + 11];
114 sprintf(command, "file -b '%s'", path);
115 FILE *f = popen(command, "r");
116 if (f) {
117 fgets(line, sizeof(line), f);
118 char *eol = line + strlen(line);
119 for (p = line; p < eol; p++) *p = tolower(*p);
120 p = strstr(line, "script text");
121 if (p && p == line) { // /^script text(?: executable)? for \w/
122 p = strstr(line, "for ");
123 if (p) {
124 p += 4;
125 pe = p;
126 while (isalnum(*pe)) pe++;
127 length = pe - p;
128 strncpy(buf, p, length);
129 buf[length] = '\0';
130 struct LanguageMap *rl = ohcount_hash_language_from_name(buf, length);
131 if (rl) language = rl->name;
132 }
133 } else if (p) { // /(\w+)(?: -\w+)* script text/
134 do {
135 p--;
136 pe = p;
137 while (*p == ' ') p--;
138 while (p != line && isalnum(*(p - 1))) p--;
139 if (p != line && *(p - 1) == '-') p--;
140 } while (*p == '-'); // Skip over any switches.
141 length = pe - p;
142 strncpy(buf, p, length);
143 buf[length] = '\0';
144 struct LanguageMap *rl = ohcount_hash_language_from_name(buf, length);
145 if (rl) language = rl->name;
146 } else if (strstr(line, "xml")) language = LANG_XML;
147 pclose(f);
148 if (tmpfile) {
149 remove(path);
150 free(path);
151 }
152 if (language) return language;
153 }
154
155 return NULL;
220 if (rd) language = rd->value(sourcefile);
221 } else language = ISBINARY(language) ? NULL : language;
222 }
223 return language;
156224 }
157225
158226 const char *disambiguate_aspx(SourceFile *sourcefile) {
184252 return LANG_CS_ASPX;
185253 }
186254
255 // 6502 assembly or XML-based Advanced Stream Redirector ?
256 const char *disambiguate_asx(SourceFile *sourcefile) {
257 char *p = ohcount_sourcefile_get_contents(sourcefile);
258 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
259 for (; p < eof; p++) {
260 switch (*p) {
261 case ' ':
262 case '\t':
263 case '\n':
264 case '\r':
265 break;
266 case '<':
267 case '\0':
268 // byte-order marks:
269 case (char) 0xef:
270 case (char) 0xfe:
271 case (char) 0xff:
272 return NULL; // XML
273 default:
274 return LANG_ASSEMBLER;
275 }
276 }
277 return LANG_ASSEMBLER; // only blanks - not valid XML, may be valid asm
278 }
279
187280 const char *disambiguate_b(SourceFile *sourcefile) {
188281 char *p = ohcount_sourcefile_get_contents(sourcefile);
189282 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
254347 }
255348
256349 // Attempt to detect from associated VB files in file context.
257 char **filenames = ohcount_sourcefile_get_filenames(sourcefile);
350 char **filenames = sourcefile->filenames;
258351 if (filenames) {
259352 int i;
260353 for (i = 0; filenames[i] != NULL; i++) {
285378 return LANG_CSHARP;
286379 }
287380
381 const char *disambiguate_dat(SourceFile *sourcefile) {
382 char *p = ohcount_sourcefile_get_contents(sourcefile);
383 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
384 for (; p < eof; p++) {
385 switch (*p) {
386 case ' ':
387 case '\t':
388 case '\n':
389 case '\r':
390 break;
391 case '/':
392 if (p[1] == '*') // AMPL comment
393 return LANG_AMPL;
394 return NULL;
395 case '#':
396 return LANG_AMPL; // AMPL comment
397 case 'd':
398 if (strncmp(p, "data", 4) == 0) // AMPL data statement
399 return LANG_AMPL;
400 return BINARY;
401 case 'p':
402 if (strncmp(p, "param", 5) == 0) // AMPL param statement
403 return LANG_AMPL;
404 return BINARY;
405 case 's':
406 if (strncmp(p, "set", 3) == 0) // AMPL set statement
407 return LANG_AMPL;
408 return BINARY;
409 default:
410 return BINARY;
411 }
412 }
413 return NULL; // only blanks
414 }
415
416 const char *disambiguate_def(SourceFile *sourcefile) {
417 char *p = ohcount_sourcefile_get_contents(sourcefile);
418 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
419 for (; p < eof; p++) {
420 switch (*p) {
421 case ' ':
422 case '\t':
423 case '\n':
424 case '\r':
425 break;
426 case '(':
427 if (p[1] == '*') // Modula-2 comment
428 return LANG_MODULA2;
429 return NULL;
430 case 'D':
431 if (strncmp(p, "DEFINITION", 10) == 0) // Modula-2 "DEFINITION MODULE"
432 return LANG_MODULA2;
433 return NULL;
434 default:
435 return NULL; // not Modula-2
436 }
437 }
438 return NULL; // only blanks
439 }
440
288441 const char *disambiguate_fortran(SourceFile *sourcefile) {
289 char *p, *pe;
442 char *p;
290443
291444 p = ohcount_sourcefile_get_contents(sourcefile);
292445 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
446
447 // Try the assumption of a fixed formatted source code, and return free
448 // format if anything opposes this assumption.
449 // Rules based on the Fortran standard, page 47:
450 // ftp://ftp.nag.co.uk/sc22wg5/N1801-N1850/N1830.pdf
293451 while (p < eof) {
294 if (*p == ' ' && p + 5 < eof) {
295 int i;
296 for (i = 1; i <= 5; i++)
297 if (!isdigit(*(p + i)) && *(p + i) != ' ')
298 return LANG_FORTRANFIXED; // definately not f77
299 // Possibly fixed (doesn't match /^\s*\d+\s*$/).
300 pe = p;
301 while (*pe == ' ' || *pe == '\t') pe++;
302 if (pe - p <= 5) {
303 if (!isdigit(*pe))
304 return LANG_FORTRANFIXED;
305 while (isdigit(*pe)) pe++;
306 while (*pe == ' ' || *pe == '\t') pe++;
307 if (*pe != '\r' && *pe != '\n' && pe - p == 5)
308 return LANG_FORTRANFIXED;
309 }
310 }
311 while (*p != '\r' && *p != '\n' && *p != '&' && p < eof) p++;
312 if (*p == '&') {
313 p++;
314 // Look for free-form continuation.
315 while (*p == ' ' || *p == '\t') p++;
316 if (*p == '\r' || *p == '\n') {
317 pe = p;
318 while (*pe == '\r' || *pe == '\n' || *pe == ' ' || *pe == '\t') pe++;
319 if (*pe == '&')
452 int i = 1;
453 int blanklabel;
454 // Process a single line; tabulators are not valid in Fortran code
455 // but some compilers accept them to skip the first 5 columns.
456 if (*p == ' ' || *p == '\t' || isdigit(*p)) {
457 // Only consider lines starting with a blank or digit
458 // (non-comment in fixed)
459 if (*p == '\t') i = 5;
460 blanklabel = (*p == ' ' || *p == '\t');
461 while (*p != '\r' && *p != '\n' && p < eof) {
462 p++; i++;
463 if (i <= 5) {
464 blanklabel = blanklabel && (*p == ' ');
465 if ( !isdigit(*p) && *p != ' ' && *p != '!')
466 // Non-digit, non-blank, non-comment character in the label field
467 // definetly not valid fixed formatted code!
468 return LANG_FORTRANFREE;
469 }
470 if ((i == 6) && !blanklabel && *p != ' ' && *p != '0')
471 // Fixed format continuation line with non-blank label field
472 // not allowed, assume free format:
320473 return LANG_FORTRANFREE;
321 }
322 }
323 while (*p == '\r' || *p == '\n') p++;
324 }
325 return LANG_FORTRANFREE; // might as well be free-form
474 // Ignore comments (a ! character in column 6 is a continuation in
475 // fixed form)
476 if (*p == '!' && i != 6) {
477 while (*p != '\r' && *p != '\n' && p < eof) p++;
478 } else {
479 // Ignore quotes
480 if (*p == '"') {
481 if (p < eof) {p++; i++;}
482 while (*p != '"' && *p != '\r' && *p != '\n' && p < eof) {
483 p++; i++;
484 }
485 }
486 if (*p == '\'') {
487 if (p < eof) {p++; i++;}
488 while (*p != '\'' && *p != '\r' && *p != '\n' && p < eof) {
489 p++; i++;
490 }
491 }
492 // Check for free format line continuation
493 if (i > 6 && i <= 72 && *p == '&')
494 // Found an unquoted free format continuation character in the fixed
495 // format code section. This has to be free format.
496 return LANG_FORTRANFREE;
497 }
498 }
499 } else {
500 // Not a statement line in fixed format...
501 if (*p != 'C' && *p != 'c' && *p != '*' && *p != '!')
502 // Not a valid fixed form comment, has to be free formatted source
503 return LANG_FORTRANFREE;
504 // Comment in fixed form, ignore this line
505 while (*p != '\r' && *p != '\n' && p < eof) p++;
506 }
507 // Skip all line ends
508 while ((*p == '\r' || *p == '\n') && p < eof) p++;
509 }
510 // Assume fixed format if none of the lines broke the assumptions
511 return LANG_FORTRANFIXED;
326512 }
327513
328514 const char *disambiguate_h(SourceFile *sourcefile) {
329 char *p, *pe;
515 char *p, *pe, *bof;
330516 int length;
331517
332518 // If the directory contains a matching *.m file, likely Objective C.
336522 strncpy(path, sourcefile->filename, length);
337523 path[length] = '\0';
338524 *(path + length - 1) = 'm';
339 char **filenames = ohcount_sourcefile_get_filenames(sourcefile);
525 char **filenames = sourcefile->filenames;
340526 if (filenames) {
341527 int i;
342528 for (i = 0; filenames[i] != NULL; i++)
347533
348534 // Attempt to detect based on file contents.
349535 char line[81], buf[81];
350 p = ohcount_sourcefile_get_contents(sourcefile);
536 bof = ohcount_sourcefile_get_contents(sourcefile);
537 p = bof;
351538 pe = p;
352539 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
353540 while (pe < eof) {
394581 // Look for C++ keywords.
395582 p = line;
396583 while (p < eol) {
397 if (islower(*p) && p != line && !isalnum(*(p - 1)) && *(p - 1) != '_') {
584 if (islower(*p) && p != bof && !isalnum(*(p - 1)) && *(p - 1) != '_') {
398585 pe = p;
399586 while (islower(*pe)) pe++;
400587 if (!isalnum(*pe) && *pe != '_') {
434621 char buf[length];
435622 strncpy(buf, p, length);
436623 buf[length] = '\0';
437 SourceFile *undecorated = ohcount_sourcefile_new(buf);
438624 p = ohcount_sourcefile_get_contents(sourcefile);
439625 if (!p) {
440626 return NULL;
441627 }
442 // The filepath without the '.in' extension does not exist on disk. The
443 // sourcefile->diskpath field must be set incase the detector needs to run
444 // 'file -b' on the file.
445 ohcount_sourcefile_set_diskpath(undecorated, sourcefile->filepath);
628
629 // A SourceFile's filepath and diskpath need not be the same.
630 // Here, we'll take advantage of this to set up a new SourceFile
631 // whose filepath does not have the *.in extension, but whose
632 // diskpath still points back to the original file on disk (if any).
633 SourceFile *undecorated = ohcount_sourcefile_new(buf);
634 if (sourcefile->diskpath) {
635 ohcount_sourcefile_set_diskpath(undecorated, sourcefile->diskpath);
636 }
446637 ohcount_sourcefile_set_contents(undecorated, p);
447 char **filenames = ohcount_sourcefile_get_filenames(sourcefile);
448 ohcount_sourcefile_set_filenames(undecorated, filenames);
638 undecorated->filenames = sourcefile->filenames;
449639 language = ohcount_sourcefile_get_language(undecorated);
450640 ohcount_sourcefile_free(undecorated);
451641 }
472662 int length;
473663
474664 // Attempt to detect based on a weighted heuristic of file contents.
665 int mathematica_score = 0;
475666 int matlab_score = 0;
476667 int objective_c_score = 0;
477668 int limbo_score = 0;
478669 int octave_syntax_detected = 0;
479670
480671 int i, has_h_headers = 0, has_c_files = 0;
481 char **filenames = ohcount_sourcefile_get_filenames(sourcefile);
672 char **filenames = sourcefile->filenames;
482673 if (filenames) {
483674 for (i = 0; filenames[i] != NULL; i++) {
484675 p = filenames[i];
529720 while (*p == ' ' || *p == '\t') p++;
530721 if (*p == '%') { // Matlab comment
531722 matlab_score++;
532 } else if (*p == '#' && strncmp(p, "#import", 7) == 0) { // Objective C
533 objective_c_score++;
723 } else if (*p == '#' && strncmp(p, "#import", 7) == 0) { // Objective C
724 objective_c_score++;
534725 } else if (*p == '#') { // Limbo or Octave comment
535726 while (*p == '#') p++;
536727 if (*p == ' ' || *p == '\t') {
538729 matlab_score++;
539730 octave_syntax_detected = 1;
540731 }
541 } else if (*p == '/' && *(p + 1) == '/' || *(p + 1) == '*') {
732 } else if (*p == '/' && *(p + 1) == '/' || *p == '/' && *(p + 1) == '*') {
542733 objective_c_score++; // Objective C comment
543734 } else if (*p == '+' || *p == '-') { // Objective C method signature
544735 objective_c_score++;
600791 } else p++;
601792 }
602793
794 // Look for Mathematica pattern definitions
795 p = line;
796 while (p < eol) {
797 // & as postfix operator
798 if (*p == '&') {
799 p++;
800 while (*p == ' ' || *p == '\t') p++;
801 if (*p == ',' || *p == ')' || *p == ']') mathematica_score++;
802 }
803 // Mathematica comment
804 if (*p == '(' && *(p + 1) == '*') mathematica_score++;
805 // some Mathematica operators
806 if (*p == '/' && *(p + 1) == '.') mathematica_score++;
807 if (*p == '_' && *(p + 1) == '_') mathematica_score++;
808 if (*p == '@' && *(p + 1) == '@') mathematica_score++;
809 p++;
810 }
811
603812 // Next line.
604813 pe = line_end;
605814 while (*pe == '\r' || *pe == '\n') pe++;
606815 p = pe;
607816 }
608817
609 if (limbo_score > objective_c_score && limbo_score > matlab_score)
818 if (limbo_score > objective_c_score &&
819 limbo_score > matlab_score &&
820 limbo_score > mathematica_score)
610821 return LANG_LIMBO;
611 else if (objective_c_score > matlab_score)
822 else if (objective_c_score > matlab_score &&
823 objective_c_score > mathematica_score)
612824 return LANG_OBJECTIVE_C;
825 else if (mathematica_score > matlab_score)
826 return LANG_MATHEMATICA;
613827 else
614828 return octave_syntax_detected ? LANG_OCTAVE : LANG_MATLAB;
829 }
830
831 const char *disambiguate_mod(SourceFile *sourcefile) {
832 char *p = ohcount_sourcefile_get_contents(sourcefile);
833 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
834 for (; p < eof; p++) {
835 switch (*p) {
836 case ' ':
837 case '\t':
838 case '\n':
839 case '\r':
840 break;
841 case '(':
842 if (p[1] == '*') // Modula-2 comment
843 return LANG_MODULA2;
844 return NULL;
845 case 'I':
846 if (strncmp(p, "IMPLEMENTATION", 14) == 0) // Modula-2 "IMPLEMENTATION MODULE"
847 return LANG_MODULA2;
848 return NULL;
849 case 'M':
850 if (strncmp(p, "MODULE", 6) == 0) // Modula-2 "MODULE"
851 return LANG_MODULA2;
852 return NULL;
853 default:
854 return LANG_AMPL;
855 }
856 }
857 return NULL; // only blanks
858 }
859
860 #include <pcre.h>
861
862 // strnlen is not available on OS X, so we roll our own
863 size_t mystrnlen(const char *begin, size_t maxlen) {
864 if (begin == NULL)
865 return 0;
866 const char *end = memchr(begin, '\0', maxlen);
867 return end ? (end - begin) : maxlen;
868 }
869
870 const char *disambiguate_pp(SourceFile *sourcefile) {
871 char *p = ohcount_sourcefile_get_contents(sourcefile);
872
873 if (!p)
874 return NULL;
875
876 /* prepare regular expressions */
877 const char *error;
878 int erroffset;
879
880 /* try harder with optional spaces */
881 pcre *keyword;
882 keyword = pcre_compile("^\\s*(ensure|content|notify|require|source)\\s+=>",
883 PCRE_MULTILINE, &error, &erroffset, NULL);
884
885 if (pcre_exec(keyword, NULL, p, mystrnlen(p, 10000), 0, 0, NULL, 0) > -1)
886 return LANG_PUPPET;
887
888 /* check for standard puppet constructs */
889 pcre *construct;
890 construct = pcre_compile("^\\s*(define\\s+[\\w:-]+\\s*\\(|class\\s+[\\w:-]+(\\s+inherits\\s+[\\w:-]+)?\\s*[\\({]|node\\s+\\'?[\\w:\\.-]+\\'?\\s*{|import\\s+\"|include\\s+[\"']?[\\w:-][\"']?)",
891 PCRE_MULTILINE, &error, &erroffset, NULL);
892
893 if (pcre_exec(construct, NULL, p, mystrnlen(p, 10000), 0, 0, NULL, 0) > -1)
894 return LANG_PUPPET;
895
896 return LANG_PASCAL;
897 }
898
899 const char *disambiguate_pl(SourceFile *sourcefile) {
900 char *contents = ohcount_sourcefile_get_contents(sourcefile);
901 if (!contents)
902 return NULL;
903
904 // Check for a perl shebang on first line of file
905 const char *error;
906 int erroffset;
907 pcre *re = pcre_compile("#![^\\n]*perl", PCRE_CASELESS, &error, &erroffset, NULL);
908 if (pcre_exec(re, NULL, contents, mystrnlen(contents, 100), 0, PCRE_ANCHORED, NULL, 0) > -1)
909 return LANG_PERL;
910
911 // Check for prolog :- rules
912 if (strstr(contents, ":- ") || strstr(contents, ":-\n"))
913 return LANG_PROLOG;
914
915 // Perl by default.
916 return LANG_PERL;
615917 }
616918
617919 #define QMAKE_SOURCES_SPACE "SOURCES +="
632934 return LANG_IDL_PVWAVE;
633935 }
634936
937 const char *disambiguate_r(SourceFile *sourcefile) {
938 char *contents = ohcount_sourcefile_get_contents(sourcefile);
939 if (!contents)
940 return LANG_R;
941
942 char *eof = contents + ohcount_sourcefile_get_contents_size(sourcefile);
943
944 // Detect REBOL by looking for the occurence of "rebol" in the contents
945 // (case-insensitive). Correct REBOL scripts have a "REBOL [...]" header
946 // block.
947 char *needle = "rebol";
948 int len = strlen(needle);
949 for (; contents < eof - len; ++contents)
950 if (tolower(*contents) == *needle &&
951 !strncasecmp(contents, needle, len))
952 return LANG_REBOL;
953
954 return LANG_R;
955 }
956
957 const char *disambiguate_rs(SourceFile *sourcefile) {
958 // .rs is normally Rust, but it might be RenderScript. RenderScript is
959 // expected to have a "#pragma version(1)" line at the very start, possibly
960 // after comments. To help with supporting future versions of RenderScript,
961 // we'll skip the number part.
962 // As RenderScript is not implemented in ohcount yet, it's returned as NULL.
963 char *contents = ohcount_sourcefile_get_contents(sourcefile);
964 if (!contents) {
965 return LANG_RUST;
966 }
967
968 char *needle = "\n#pragma version";
969 int len = strlen(needle);
970 if (strncasecmp(contents, needle + 1, len - 1) == 0) {
971 // "#pragma version" at the very start of the file is RenderScript.
972 return NULL;
973 }
974
975 char *eof = contents + ohcount_sourcefile_get_contents_size(sourcefile);
976
977 for (; contents < eof - len; ++contents) {
978 if (!strncmp(contents, needle, len)) {
979 return NULL;
980 }
981 }
982
983 return LANG_RUST;
984 }
985
635986 const char *disambiguate_st(SourceFile *sourcefile) {
636987 char *p, *pe;
637988 int length;
645996 char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
646997 while (pe < eof) {
647998 // Get a line at a time.
648 while (p < eof && *pe != '\r' && *pe != '\n') pe++;
999 while (pe < eof && *pe != '\r' && *pe != '\n') pe++;
6491000 length = (pe - p <= sizeof(line)) ? pe - p : sizeof(line);
6501001 strncpy(line, p, length);
6511002 line[length] = '\0';
3030
3131 int ohcount_is_binary_filename(const char *filename);
3232
33 /* Exported for unit testing */
34 void escape_path(char *safe, const char *unsafe);
35
3336 #endif
00 #include <stdio.h>
11 #include <unistd.h>
22 #include <errno.h>
3
4 #ifdef _WIN32
5 # include <fcntl.h>
6 # define mkstemp(p) _open(_mktemp(p), _O_CREAT | _O_SHORT_LIVED | _O_EXCL)
7 #endif
38
49 /*
510 * The bulk of this software is derived from Plan 9 and is thus distributed
618623 char *tmp_file_from_buf(const char *buf) {
619624 char *template = "/tmp/ohcount_diff_XXXXXXX";
620625 char *path = strdup(template);
621
626
622627 int fd = mkstemp(path);
623 write(fd, buf, strlen(buf));
628 if (write(fd, buf, strlen(buf)) != strlen(buf)) {
629 fprintf(stderr, "src/diff.c: Could not write temporary file %s.\n", path);
630 exit(1);
631 }
624632 close(fd);
625633 return path;
626634 }
22 #include "../sourcefile.h"
33
44 const char *disambiguate_aspx(SourceFile *sourcefile);
5 const char *disambiguate_asx(SourceFile *sourcefile);
56 const char *disambiguate_b(SourceFile *sourcefile);
67 const char *disambiguate_basic(SourceFile *sourcefile);
78 const char *disambiguate_cs(SourceFile *sourcefile);
9 const char *disambiguate_dat(SourceFile *sourcefile);
10 const char *disambiguate_def(SourceFile *sourcefile);
811 const char *disambiguate_fortran(SourceFile *sourcefile);
912 const char *disambiguate_h(SourceFile *sourcefile);
1013 const char *disambiguate_in(SourceFile *sourcefile);
1114 const char *disambiguate_inc(SourceFile *sourcefile);
1215 const char *disambiguate_m(SourceFile *sourcefile);
16 const char *disambiguate_mod(SourceFile *sourcefile);
17 const char *disambiguate_pl(SourceFile *sourcefile);
18 const char *disambiguate_pp(SourceFile *sourcefile);
1319 const char *disambiguate_pro(SourceFile *sourcefile);
20 const char *disambiguate_r(SourceFile *sourcefile);
21 const char *disambiguate_rs(SourceFile *sourcefile);
1422 const char *disambiguate_st(SourceFile *sourcefile);
1523 %}
1624 struct DisambiguateFuncsMap { const char *key; const char* (*value)(SourceFile*); };
1725 %%
1826 aspx, disambiguate_aspx
27 asx, disambiguate_asx
1928 b, disambiguate_b
2029 basic, disambiguate_basic
2130 cs, disambiguate_cs
31 dat, disambiguate_dat
32 def, disambiguate_def
2233 fortran, disambiguate_fortran
2334 h, disambiguate_h
2435 in, disambiguate_in
2536 inc, disambiguate_inc
2637 m, disambiguate_m
38 mod, disambiguate_mod
39 pl, disambiguate_pl
40 pp, disambiguate_pp
2741 pro, disambiguate_pro
42 r, disambiguate_r
43 rs, disambiguate_rs
2844 st, disambiguate_st
55 %}
66 struct ExtensionMap { const char *key; const char *value; };
77 %%
8 4th, LANG_FORTH
89 C, LANG_CPP
910 H, LANG_CPP
1011 ada, LANG_ADA
1213 ads, LANG_ADA
1314 aiff, BINARY
1415 as, LANG_ACTIONSCRIPT
16 as8, LANG_ASSEMBLER
1517 ascx, DISAMBIGUATE("aspx")
1618 asm, LANG_ASSEMBLER
1719 aspx, DISAMBIGUATE("aspx")
20 asx, DISAMBIGUATE("asx")
1821 au, BINARY
22 aug, LANG_AUGEAS
1923 avi, BINARY
2024 awk, LANG_AWK
2125 b, DISAMBIGUATE("b")
2226 bas, DISAMBIGUATE("basic")
2327 bat, LANG_BAT
28 bf, LANG_BRAINFUCK
29 bfpp, LANG_BFPP
2430 bi, DISAMBIGUATE("basic")
2531 bmp, BINARY
2632 bmx, LANG_BLITZMAX
2935 c++, LANG_CPP
3036 cache, BINARY
3137 cc, LANG_CPP
38 chai, LANG_CHAISCRIPT
39 clj, LANG_CLOJURE
40 cls, LANG_TEX
3241 cmake, LANG_CMAKE
42 coffee, LANG_COFFEESCRIPT
3343 com, LANG_DCL
3444 cpp, LANG_CPP
3545 cs, DISAMBIGUATE("cs")
3646 csproj, LANG_XML
3747 css, LANG_CSS
3848 ctp, LANG_PHP
49 cu, LANG_CUDA
3950 cxx, LANG_CPP
4051 d, LANG_DMD
41 dat, BINARY
52 dat, DISAMBIGUATE("dat")
53 def, DISAMBIGUATE("def")
4254 di, LANG_DMD
4355 doc, BINARY
56 dtx, LANG_TEX_DTX
4457 dylan, LANG_DYLAN
4558 e, LANG_EIFFEL
4659 ebuild, LANG_EBUILD
60 ec, LANG_EC
4761 eclass, LANG_EBUILD
62 eh, LANG_EC
4863 el, LANG_EMACSLISP
4964 erl, LANG_ERLANG
5065 exheres-0, LANG_EXHERES
5166 exlib, LANG_EXHERES
5267 f, DISAMBIGUATE("fortran")
5368 f03, DISAMBIGUATE("fortran")
69 f08, DISAMBIGUATE("fortran")
5470 f77, DISAMBIGUATE("fortran")
5571 f90, DISAMBIGUATE("fortran")
5672 f95, DISAMBIGUATE("fortran")
5773 factor, LANG_FACTOR
74 fr, LANG_FORTH
5875 frag, LANG_GLSL
76 for, DISAMBIGUATE("fortran")
77 fpp, DISAMBIGUATE("fortran")
5978 frm, LANG_VISUALBASIC
6079 frx, LANG_VISUALBASIC
6180 fs, LANG_FSHARP
6281 ftn, DISAMBIGUATE("fortran")
82 gemspec, LANG_RUBY
6383 gif, BINARY
6484 glsl, LANG_GLSL
85 go, LANG_GOLANG
6586 groovy, LANG_GROOVY
87 grace, LANG_GRACE
88 grc, LANG_GRACE
89 gs, LANG_GENIE
6690 gz, BINARY
6791 h, DISAMBIGUATE("h")
6892 h++, LANG_CPP
7599 html, LANG_HTML
76100 hx, LANG_HAXE
77101 hxx, LANG_CPP
102 i3, LANG_MODULA3
78103 icns, BINARY
79104 in, DISAMBIGUATE("in")
80105 inc, DISAMBIGUATE("inc")
90115 lisp, LANG_LISP
91116 lsp, LANG_LISP
92117 ltx, LANG_TEX
118 lgt, LANG_LOGTALK
93119 lua, LANG_LUA
94120 m, DISAMBIGUATE("m")
121 m3, LANG_MODULA3
122 m4, LANG_AUTOCONF
95123 m4a, BINARY
96124 mf, LANG_METAFONT
97125 mk, LANG_MAKE
99127 ml4, LANG_OCAML
100128 mli, LANG_OCAML
101129 mm, LANG_OBJECTIVE_C
130 mod, DISAMBIGUATE("mod")
102131 mov, BINARY
103132 mp, LANG_METAPOST_WITH_TEX
104133 mp3, BINARY
105134 mpg, BINARY
135 mt, LANG_MATHEMATICA
136 mustache, LANG_HTML
106137 mxml, LANG_MXML
107138 nix, LANG_NIX
108139 nse, LANG_LUA
140 nsi, LANG_NSIS
141 nsh, LANG_NSIS
142 ob2, LANG_OBERON
143 obn, LANG_OBERON
109144 ogg, BINARY
110145 p6, LANG_PERL
111146 pas, LANG_PASCAL
117152 php4, LANG_PHP
118153 php5, LANG_PHP
119154 pike, LANG_PIKE
120 pl, LANG_PERL
155 pl, DISAMBIGUATE("pl")
121156 pm, LANG_PERL
122157 pmc, LANG_C
123158 pmod, LANG_PIKE
124159 png, BINARY
125160 pnt, BINARY
126161 pod, LANG_PERL
127 pp, LANG_PASCAL
162 pp, DISAMBIGUATE("pp")
128163 ppt, BINARY
129164 pro, DISAMBIGUATE("pro")
130165 py, LANG_PYTHON
166 qml, LANG_QML
131167 qt, BINARY
132 r, LANG_R
168 r, DISAMBIGUATE("r")
169 r3, LANG_REBOL
133170 ra, BINARY
134171 rb, LANG_RUBY
172 rbw, LANG_RUBY
173 reb, LANG_REBOL
174 rebol, LANG_REBOL
135175 rex, LANG_REXX
136176 rexx, LANG_REXX
137177 rhtml, LANG_RHTML
178 rkt, LANG_RACKET
179 rktd, LANG_RACKET
180 rktl, LANG_RACKET
181 rs, DISAMBIGUATE("rs")
182 ru, LANG_RUBY
183 run, LANG_AMPL
138184 s, LANG_ASSEMBLER
139185 sc, LANG_SCHEME
140186 scala, LANG_SCALA
148194 ss, LANG_SCHEME
149195 st, DISAMBIGUATE("st")
150196 str, LANG_STRATEGO
197 sty, LANG_TEX
151198 svg, BINARY
152199 svgz, BINARY
153200 svn, BINARY
160207 tif, BINARY
161208 tiff, BINARY
162209 tpl, LANG_HTML
163 txx, LANG_CPP
210 ts, LANG_TYPESCRIPT
211 tsx, LANG_TYPESCRIPT
164212 vala, LANG_VALA
213 vapi, LANG_VALA
214 v, LANG_COQ
165215 vb, LANG_VISUALBASIC
166216 vba, LANG_VISUALBASIC
167217 vbs, LANG_VISUALBASIC
170220 vhdl, LANG_VHDL
171221 vim, LANG_VIM
172222 wav, BINARY
223 wl, LANG_MATHEMATICA
224 wlt, LANG_MATHEMATICA
173225 xaml, LANG_XAML
174226 xls, BINARY
175227 xlw, BINARY
33 struct FilenameMap { const char *key; const char *value; };
44 %%
55 CMakeLists.txt, LANG_CMAKE
6 Jamfile, LANG_JAM
7 Jamrules, LANG_JAM
68 GNUmakefile, LANG_MAKE
79 Makefile, LANG_MAKE
810 Makefile.am, LANG_AUTOMAKE
911 configure, LANG_AUTOCONF
1012 configure.ac, LANG_AUTOCONF
1113 configure.in, LANG_AUTOCONF
14 init.pp, LANG_PUPPET
1215 makefile, LANG_MAKE
16 Rakefile, LANG_RUBY
17 rakefile, LANG_RUBY
18 Gemfile, LANG_RUBY
19 Vagrantfile, LANG_RUBY
00 #!/bin/sh
1
2 # Check for gperf
3 if `type gperf > /dev/null 2> /dev/null`
4 then
5 echo "Found gperf, making headers..."
6 else
7 echo "gperf not found, aborting" >&2
8 exit 1
9 fi
110
211 gperf -L ANSI-C -E -D -K key -H ohcount_hash_language -N ohcount_hash_language_from_name -t languages.gperf > language_hash.c
312 gperf -L ANSI-C -E -D -K key -H ohcount_hash_extension -N ohcount_hash_language_from_ext -t extensions.gperf > extension_hash.h
44 %%
55 actionscript, LANG_ACTIONSCRIPT, "ActionScript", 0
66 ada, LANG_ADA, "Ada", 0
7 ampl, LANG_AMPL, "AMPL", 0
78 assembler, LANG_ASSEMBLER, "Assembler", 0
9 augeas, LANG_AUGEAS, "Augeas", 0
810 autoconf, LANG_AUTOCONF, "Autoconf", 2
911 automake, LANG_AUTOMAKE, "Automake", 2
1012 awk, LANG_AWK, "AWK", 0
1113 bat, LANG_BAT, "DOS batch script", 0
14 bash, LANG_SHELL, "shell script", 0
1215 blitzmax, LANG_BLITZMAX, "BlitzMax", 0
1316 boo, LANG_BOO, "Boo", 0
17 brainfuck, LANG_BRAINFUCK, "Brainfuck", 0
18 bfpp, LANG_BFPP, "Brainfuck++", 0
1419 c, LANG_C, "C", 0
20 chaiscript, LANG_CHAISCRIPT, "ChaiScript", 0
1521 classic_basic, LANG_CLASSIC_BASIC, "Classic Basic", 0
1622 clearsilver, LANG_CLEARSILVER, "ClearSilver", 0
1723 clearsilver_template, LANG_CLEARSILVER_TEMPLATE, "ClearSilver", 0
24 clojure, LANG_CLOJURE, "Clojure", 0
1825 cmake, LANG_CMAKE, "Cmake script", 2
26 coffescript, LANG_COFFEESCRIPT, "CoffeeScript", 0
27 coq, LANG_COQ, "Coq", 0
1928 cpp, LANG_CPP, "C++", 0
2029 cs_aspx, LANG_CS_ASPX, "", 0
2130 csharp, LANG_CSHARP, "C#", 0
2231 css, LANG_CSS, "CSS", 1
32 cuda, LANG_CUDA, "CUDA", 0
2333 dcl, LANG_DCL, "DCL", 0
2434 dmd, LANG_DMD, "D", 0
35 dtx, LANG_TEX_DTX, "DTX for TeX/LaTeX", 1
2536 dylan, LANG_DYLAN, "Dylan", 0
2637 ebuild, LANG_EBUILD, "Ebuild", 0
38 ec, LANG_EC, "eC", 0
2739 eiffel, LANG_EIFFEL, "Eiffel", 0
2840 emacslisp, LANG_EMACSLISP, "Emacs lisp", 0
2941 erlang, LANG_ERLANG, "Erlang", 0
3042 exheres, LANG_EXHERES, "Exheres", 0
3143 factor, LANG_FACTOR, "Factor", 0
44 forth, LANG_FORTH, "Forth", 0
3245 fortranfixed, LANG_FORTRANFIXED, "Fortan (Fixed-format)", 0
3346 fortranfree, LANG_FORTRANFREE, "Fortan (Free-format)", 0
3447 fsharp, LANG_FSHARP, "F#", 0
48 genie, LANG_GENIE, "Genie", 0
3549 glsl, LANG_GLSL, "OpenGL Shading Language", 0
50 golang, LANG_GOLANG, "Golang", 0
51 grace, LANG_GRACE, "Grace", 0
3652 groovy, LANG_GROOVY, "Groovy", 0
3753 haml, LANG_HAML, "Haml", 1
3854 haskell, LANG_HASKELL, "Haskell", 0
3955 haxe, LANG_HAXE, "HaXe", 0
4056 html, LANG_HTML, "HTML", 1
4157 idl_pvwave, LANG_IDL_PVWAVE, "IDL/PV-WAVE/GDL", 0
58 jam, LANG_JAM, "Jam", 2
4259 java, LANG_JAVA, "Java", 0
4360 javascript, LANG_JAVASCRIPT, "JavaScript", 0
4461 jsp, LANG_JSP, "", 0
4562 limbo, LANG_LIMBO, "Limbo", 0
4663 lisp, LANG_LISP, "Lisp", 0
64 logtalk, LANG_LOGTALK, "Logtalk", 0
4765 lua, LANG_LUA, "Lua", 0
4866 make, LANG_MAKE, "Make", 2
67 mathematica, LANG_MATHEMATICA, "Mathematica", 0
4968 matlab, LANG_MATLAB, "Matlab", 0
5069 metafont, LANG_METAFONT, "MetaFont", 1
5170 metapost, LANG_METAPOST, "MetaPost", 1
5271 metapost_with_tex, LANG_METAPOST_WITH_TEX, "", 0
72 modula2, LANG_MODULA2, "Modula-2", 0
73 modula3, LANG_MODULA3, "Modula-3", 0
5374 mxml, LANG_MXML, "MXML", 1
5475 nix, LANG_NIX, "Nix", 0
76 nsis, LANG_NSIS, "NSIS", 0
77 oberon, LANG_OBERON, "Oberon", 0
5578 objective_c, LANG_OBJECTIVE_C, "Objective-C", 0
5679 objective_j, LANG_OBJECTIVE_J, "Objective-J", 0
5780 ocaml, LANG_OCAML, "Objective Caml", 0
6083 perl, LANG_PERL, "Perl", 0
6184 php, LANG_PHP, "PHP", 0
6285 pike, LANG_PIKE, "Pike", 0
86 prolog, LANG_PROLOG, "Prolog", 0
87 puppet, LANG_PUPPET, "Puppet", 0
6388 python, LANG_PYTHON, "Python", 0
89 qml, LANG_QML, "QML", 1
6490 r, LANG_R, "R", 0
91 racket, LANG_RACKET, "Racket", 0
92 rebol, LANG_REBOL, "REBOL", 0
6593 rexx, LANG_REXX, "rexx", 0
6694 rhtml, LANG_RHTML, "", 0
6795 ruby, LANG_RUBY, "Ruby", 0
96 rust, LANG_RUST, "Rust", 0
6897 scala, LANG_SCALA, "Scala", 0
6998 scheme, LANG_SCHEME, "Scheme", 0
7099 scilab, LANG_SCILAB, "Scilab", 0
75104 sql, LANG_SQL, "SQL", 0
76105 tcl, LANG_TCL, "TCL", 0
77106 tex, LANG_TEX, "TeX/LaTeX", 1
107 typescript, LANG_TYPESCRIPT, "TypeScript", 0
78108 vala, LANG_VALA, "Vala", 0
79109 vb_aspx, LANG_VB_ASPX, "", 0
80110 vhdl, LANG_VHDL, "VHDL", 0
00 %{
11 #include "../parsers/actionscript.h"
22 #include "../parsers/ada.h"
3 #include "../parsers/ampl.h"
34 #include "../parsers/assembler.h"
5 #include "../parsers/augeas.h"
46 #include "../parsers/autoconf.h"
57 #include "../parsers/automake.h"
68 #include "../parsers/awk.h"
79 #include "../parsers/bat.h"
810 #include "../parsers/blitzmax.h"
911 #include "../parsers/boo.h"
12 #include "../parsers/brainfuck.h"
13 #include "../parsers/bfpp.h"
1014 #include "../parsers/c.h"
15 #include "../parsers/chaiscript.h"
1116 #include "../parsers/classic_basic.h"
1217 #include "../parsers/clearsilver.h"
1318 #include "../parsers/clearsilverhtml.h"
19 #include "../parsers/coffeescript.h"
1420 #include "../parsers/cmake.h"
21 #include "../parsers/coq.h"
1522 #include "../parsers/cs_aspx.h"
1623 #include "../parsers/css.h"
1724 #include "../parsers/d.h"
2229 #include "../parsers/erlang.h"
2330 #include "../parsers/exheres.h"
2431 #include "../parsers/factor.h"
32 #include "../parsers/forth.h"
2533 #include "../parsers/fortranfixed.h"
2634 #include "../parsers/fortranfree.h"
2735 #include "../parsers/fsharp.h"
2836 #include "../parsers/glsl.h"
37 #include "../parsers/golang.h"
38 #include "../parsers/grace.h"
2939 #include "../parsers/groovy.h"
3040 #include "../parsers/haml.h"
3141 #include "../parsers/haskell.h"
3242 #include "../parsers/haxe.h"
3343 #include "../parsers/html.h"
3444 #include "../parsers/idl_pvwave.h"
45 #include "../parsers/jam.h"
3546 #include "../parsers/java.h"
3647 #include "../parsers/javascript.h"
3748 #include "../parsers/jsp.h"
3849 #include "../parsers/lisp.h"
3950 #include "../parsers/limbo.h"
51 #include "../parsers/logtalk.h"
4052 #include "../parsers/lua.h"
4153 #include "../parsers/makefile.h"
54 #include "../parsers/mathematica.h"
4255 #include "../parsers/matlab.h"
4356 #include "../parsers/metafont.h"
4457 #include "../parsers/metapost.h"
4558 #include "../parsers/metapost_with_tex.h"
59 #include "../parsers/modula2.h"
60 #include "../parsers/modula3.h"
4661 #include "../parsers/mxml.h"
4762 #include "../parsers/nix.h"
63 #include "../parsers/nsis.h"
64 #include "../parsers/oberon.h"
4865 #include "../parsers/objective_c.h"
4966 #include "../parsers/objective_j.h"
5067 #include "../parsers/ocaml.h"
5370 #include "../parsers/perl.h"
5471 #include "../parsers/phphtml.h"
5572 #include "../parsers/pike.h"
73 #include "../parsers/prolog.h"
74 #include "../parsers/puppet.h"
5675 #include "../parsers/python.h"
5776 #include "../parsers/r.h"
77 #include "../parsers/rebol.h"
5878 #include "../parsers/rexx.h"
5979 #include "../parsers/ruby.h"
80 #include "../parsers/rust.h"
6081 #include "../parsers/rhtml.h"
6182 #include "../parsers/scala.h"
6283 #include "../parsers/scilab.h"
6788 #include "../parsers/sql.h"
6889 #include "../parsers/tcl.h"
6990 #include "../parsers/tex.h"
91 #include "../parsers/tex_dtx.h"
7092 #include "../parsers/vb_aspx.h"
7193 #include "../parsers/vhdl.h"
7294 #include "../parsers/vim.h"
80102 %%
81103 actionscript, parse_actionscript
82104 ada, parse_ada
105 ampl, parse_ampl
83106 assembler, parse_assembler
107 augeas, parse_augeas
84108 autoconf, parse_autoconf
85109 automake, parse_automake
86110 awk, parse_awk
87111 bat, parse_bat
88112 blitzmax, parse_blitzmax
89113 boo, parse_boo
114 brainfuck, parse_brainfuck
115 bfpp, parse_bfpp
90116 c, parse_c
117 chaiscript, parse_chaiscript
91118 cmake, parse_cmake
92119 classic_basic, parse_classic_basic
93120 clearsilver, parse_clearsilver
94121 clearsilver_template, parse_cshtml
122 clojure, parse_clojure
123 coffeescript, parse_coffeescript
124 coq, parse_coq
95125 cpp, parse_cpp
96126 cs_aspx, parse_cs_aspx
97127 csharp, parse_csharp
98128 css, parse_css
129 cuda, parse_cuda
99130 dcl, parse_dcl
100131 dmd, parse_d
101132 dylan, parse_dylan
102133 ebuild, parse_ebuild
134 ec, parse_ec
103135 eiffel, parse_eiffel
104136 erlang, parse_erlang
105137 exheres, parse_exheres
106138 emacslisp, parse_emacslisp
107139 factor, parse_factor
140 forth, parse_forth
108141 fortranfixed, parse_fortranfixed
109142 fortranfree, parse_fortranfree
110143 fsharp, parse_fsharp
144 genie, parse_genie
111145 glsl, parse_glsl
146 golang, parse_golang
147 grace, parse_grace
112148 groovy, parse_groovy
113149 haskell, parse_haskell
114150 haml, parse_haml
115151 haxe, parse_haxe
116152 html, parse_html
117153 idl_pvwave, parse_idl_pvwave
154 jam, parse_jam
118155 java, parse_java
119156 javascript, parse_javascript
120157 jsp, parse_jsp
121158 lisp, parse_lisp
122159 limbo, parse_limbo
160 logtalk, parse_logtalk
123161 lua, parse_lua
124162 make, parse_makefile
163 mathematica, parse_mathematica
125164 matlab, parse_matlab
126165 metafont, parse_metafont
127166 metapost, parse_metapost
128167 metapost_with_tex, parse_mptex
168 modula2, parse_modula2
169 modula3, parse_modula3
129170 mxml, parse_mxml
130171 nix, parse_nix
172 nsis, parse_nsis
173 oberon, parse_oberon
131174 objective_c, parse_objective_c
132175 objective_j, parse_objective_j
133176 ocaml, parse_ocaml
136179 perl, parse_perl
137180 php, parse_phtml
138181 pike, parse_pike
182 prolog, parse_prolog
183 puppet, parse_puppet
139184 python, parse_python
185 qml, parse_qml
140186 r, parse_r
187 racket, parse_racket
188 rebol, parse_rebol
141189 rexx, parse_rexx
142190 rhtml, parse_rhtml
143191 ruby, parse_ruby
192 rust, parse_rust
144193 scala, parse_scala
145194 scheme, parse_scheme
146195 scilab, parse_scilab
151200 sql, parse_sql
152201 tcl, parse_tcl
153202 tex, parse_tex
203 tex_dtx, parse_tex_dtx
204 typescript, parse_typescript
154205 vala, parse_vala
155206 vb_aspx, parse_vb_aspx
156207 vhdl, parse_vhdl
0 // languages.h written by Mitchell Foral. mitchell<att>caladbolg.net.
1 // See COPYING for license information.
2
3 #ifndef OHCOUNT_LANGUAGES_H
4 #define OHCOUNT_LANGUAGES_H
5
6 #include <string.h>
7
8 #define LANG_ACTIONSCRIPT "actionscript"
9 #define LANG_ADA "ada"
10 #define LANG_ASSEMBLER "assembler"
11 #define LANG_AUTOCONF "autoconf"
12 #define LANG_AUTOMAKE "automake"
13 #define LANG_AWK "awk"
14 #define LANG_BAT "bat"
15 #define LANG_BLITZMAX "blitzmax"
16 #define LANG_BOO "boo"
17 #define LANG_C "c"
18 #define LANG_CLASSIC_BASIC "classic_basic"
19 #define LANG_CLEARSILVER "clearsilver"
20 #define LANG_CLEARSILVER_TEMPLATE "clearsilver_template"
21 #define LANG_CMAKE "cmake"
22 #define LANG_CPP "cpp"
23 #define LANG_CS_ASPX "cs_aspx"
24 #define LANG_CSHARP "csharp"
25 #define LANG_CSS "css"
26 #define LANG_DCL "dcl"
27 #define LANG_DMD "dmd"
28 #define LANG_DYLAN "dylan"
29 #define LANG_EBUILD "ebuild"
30 #define LANG_EIFFEL "eiffel"
31 #define LANG_ERLANG "erlang"
32 #define LANG_EXHERES "exheres"
33 #define LANG_EMACSLISP "emacslisp"
34 #define LANG_FACTOR "factor"
35 #define LANG_FORTRANFIXED "fortranfixed"
36 #define LANG_FORTRANFREE "fortranfree"
37 #define LANG_FSHARP "fsharp"
38 #define LANG_GLSL "glsl"
39 #define LANG_GROOVY "groovy"
40 #define LANG_HASKELL "haskell"
41 #define LANG_HAML "haml"
42 #define LANG_HAXE "haxe"
43 #define LANG_HTML "html"
44 #define LANG_IDL_PVWAVE "idl_pvwave"
45 #define LANG_JAVA "java"
46 #define LANG_JAVASCRIPT "javascript"
47 #define LANG_JSP "jsp"
48 #define LANG_LIMBO "limbo"
49 #define LANG_LISP "lisp"
50 #define LANG_LUA "lua"
51 #define LANG_MAKE "make"
52 #define LANG_MATLAB "matlab"
53 #define LANG_METAFONT "metafont"
54 #define LANG_METAPOST "metapost"
55 #define LANG_METAPOST_WITH_TEX "metapost_with_tex"
56 #define LANG_MXML "mxml"
57 #define LANG_NIX "nix"
58 #define LANG_OBJECTIVE_C "objective_c"
59 #define LANG_OBJECTIVE_J "objective_j"
60 #define LANG_OCAML "ocaml"
61 #define LANG_OCTAVE "octave"
62 #define LANG_PASCAL "pascal"
63 #define LANG_PERL "perl"
64 #define LANG_PHP "php"
65 #define LANG_PIKE "pike"
66 #define LANG_PYTHON "python"
67 #define LANG_R "r"
68 #define LANG_REXX "rexx"
69 #define LANG_RHTML "rhtml"
70 #define LANG_RUBY "ruby"
71 #define LANG_SCALA "scala"
72 #define LANG_SCHEME "scheme"
73 #define LANG_SCILAB "scilab"
74 #define LANG_SHELL "shell"
75 #define LANG_SMALLTALK "smalltalk"
76 #define LANG_STRATEGO "stratego"
77 #define LANG_STRUCTURED_BASIC "structured_basic"
78 #define LANG_SQL "sql"
79 #define LANG_TCL "tcl"
80 #define LANG_TEX "tex"
81 #define LANG_VALA "vala"
82 #define LANG_VB_ASPX "vb_aspx"
83 #define LANG_VHDL "vhdl"
84 #define LANG_VIM "vim"
85 #define LANG_VISUALBASIC "visualbasic"
86 #define LANG_XAML "xaml"
87 #define LANG_XML "xml"
88 #define LANG_XSLT "xslt"
89 #define LANG_XMLSCHEMA "xmlschema"
90
91 // For gperf.
92 struct LanguageMap { const char *key; const char *name; const char *nice_name; int category; };
93 struct LanguageMap *ohcount_hash_language_from_name(register const char *str, register unsigned int len);
94
95 #endif
0 // languages.h written by Mitchell Foral. mitchell<att>caladbolg.net.
1 // See COPYING for license information.
2
3 #ifndef OHCOUNT_LANGUAGES_H
4 #define OHCOUNT_LANGUAGES_H
5
6 #include <string.h>
7
8 #define LANG_ACTIONSCRIPT "actionscript"
9 #define LANG_ADA "ada"
10 #define LANG_AMPL "ampl"
11 #define LANG_ASSEMBLER "assembler"
12 #define LANG_AUGEAS "augeas"
13 #define LANG_AUTOCONF "autoconf"
14 #define LANG_AUTOMAKE "automake"
15 #define LANG_AWK "awk"
16 #define LANG_BRAINFUCK "brainfuck"
17 #define LANG_BFPP "bfpp"
18 #define LANG_BAT "bat"
19 #define LANG_BLITZMAX "blitzmax"
20 #define LANG_BOO "boo"
21 #define LANG_C "c"
22 #define LANG_CHAISCRIPT "chaiscript"
23 #define LANG_CLASSIC_BASIC "classic_basic"
24 #define LANG_CLEARSILVER "clearsilver"
25 #define LANG_CLEARSILVER_TEMPLATE "clearsilver_template"
26 #define LANG_CLOJURE "clojure"
27 #define LANG_CMAKE "cmake"
28 #define LANG_COFFEESCRIPT "coffeescript"
29 #define LANG_COQ "coq"
30 #define LANG_CPP "cpp"
31 #define LANG_CS_ASPX "cs_aspx"
32 #define LANG_CSHARP "csharp"
33 #define LANG_CSS "css"
34 #define LANG_CUDA "cuda"
35 #define LANG_DCL "dcl"
36 #define LANG_DMD "dmd"
37 #define LANG_DYLAN "dylan"
38 #define LANG_EBUILD "ebuild"
39 #define LANG_EC "ec"
40 #define LANG_EIFFEL "eiffel"
41 #define LANG_ERLANG "erlang"
42 #define LANG_EXHERES "exheres"
43 #define LANG_EMACSLISP "emacslisp"
44 #define LANG_FACTOR "factor"
45 #define LANG_FORTH "forth"
46 #define LANG_FORTRANFIXED "fortranfixed"
47 #define LANG_FORTRANFREE "fortranfree"
48 #define LANG_FSHARP "fsharp"
49 #define LANG_GENIE "genie"
50 #define LANG_GLSL "glsl"
51 #define LANG_GOLANG "golang"
52 #define LANG_GRACE "grace"
53 #define LANG_GROOVY "groovy"
54 #define LANG_HASKELL "haskell"
55 #define LANG_HAML "haml"
56 #define LANG_HAXE "haxe"
57 #define LANG_HTML "html"
58 #define LANG_IDL_PVWAVE "idl_pvwave"
59 #define LANG_JAM "jam"
60 #define LANG_JAVA "java"
61 #define LANG_JAVASCRIPT "javascript"
62 #define LANG_JSP "jsp"
63 #define LANG_LIMBO "limbo"
64 #define LANG_LISP "lisp"
65 #define LANG_LOGTALK "logtalk"
66 #define LANG_LUA "lua"
67 #define LANG_MAKE "make"
68 #define LANG_MATHEMATICA "mathematica"
69 #define LANG_MATLAB "matlab"
70 #define LANG_METAFONT "metafont"
71 #define LANG_METAPOST "metapost"
72 #define LANG_METAPOST_WITH_TEX "metapost_with_tex"
73 #define LANG_MODULA2 "modula2"
74 #define LANG_MODULA3 "modula3"
75 #define LANG_MXML "mxml"
76 #define LANG_NIX "nix"
77 #define LANG_NSIS "nsis"
78 #define LANG_OBERON "oberon"
79 #define LANG_OBJECTIVE_C "objective_c"
80 #define LANG_OBJECTIVE_J "objective_j"
81 #define LANG_OCAML "ocaml"
82 #define LANG_OCTAVE "octave"
83 #define LANG_PASCAL "pascal"
84 #define LANG_PERL "perl"
85 #define LANG_PHP "php"
86 #define LANG_PIKE "pike"
87 #define LANG_PROLOG "prolog"
88 #define LANG_PUPPET "puppet"
89 #define LANG_PYTHON "python"
90 #define LANG_QML "qml"
91 #define LANG_R "r"
92 #define LANG_RACKET "racket"
93 #define LANG_REBOL "rebol"
94 #define LANG_REXX "rexx"
95 #define LANG_RHTML "rhtml"
96 #define LANG_RUBY "ruby"
97 #define LANG_RUST "rust"
98 #define LANG_SCALA "scala"
99 #define LANG_SCHEME "scheme"
100 #define LANG_SCILAB "scilab"
101 #define LANG_SHELL "shell"
102 #define LANG_SMALLTALK "smalltalk"
103 #define LANG_STRATEGO "stratego"
104 #define LANG_STRUCTURED_BASIC "structured_basic"
105 #define LANG_SQL "sql"
106 #define LANG_TCL "tcl"
107 #define LANG_TEX "tex"
108 #define LANG_TEX_DTX "tex_dtx"
109 #define LANG_TYPESCRIPT "typescript"
110 #define LANG_VALA "vala"
111 #define LANG_VB_ASPX "vb_aspx"
112 #define LANG_VHDL "vhdl"
113 #define LANG_VIM "vim"
114 #define LANG_VISUALBASIC "visualbasic"
115 #define LANG_XAML "xaml"
116 #define LANG_XML "xml"
117 #define LANG_XSLT "xslt"
118 #define LANG_XMLSCHEMA "xmlschema"
119
120 // For gperf.
121 struct LanguageMap { const char *key; const char *name; const char *nice_name; int category; };
122 struct LanguageMap *ohcount_hash_language_from_name(register const char *str, register unsigned int len);
123
124 #endif
717717 PCRE_MULTILINE,
718718 "(The Regents of the University of California)|(used to endorse or promote\\s+.*products\\s+.*prior\\s+.*written\\s+.*permission\\.)",
719719 PCRE_MULTILINE,
720 NULL, NULL
721 },
722 {
723 LIC_WTFPL2,
724 "",
725 "WTF Public License",
726 "(\\bwtfpl\\b)|(\\bwtf\\s*public\\s*license\\b)|(\\b(do\\s*)?what\\s*the\\s*\\fuck\\s*public\\s*license\\b)",
727 PCRE_CASELESS,
728 NULL,
729 0,
720730 NULL, NULL
721731 },
722732 { NULL, NULL, NULL, NULL, 0, NULL, 0, NULL, NULL },
9494 #define LIC_APACHE_ISH "apache_ish"
9595 #define LIC_BSD_ISH "bsd_ish"
9696 #define LIC_BSD_2CLAUSE_ISH "bsd_2clause_ish"
97 #define LIC_WTFPL2 "wtfpl_2"
9798
9899 /**
99100 * Attempts to detect the source code licenses for a given file.
172172 printf(" %10d", liter->loc->blanks);
173173 printf(" %10d",
174174 liter->loc->code + liter->loc->comments + liter->loc->blanks);
175 printf(" %s\n", iter->sf->filename);
175 printf(" %s\n", iter->sf->filepath);
176176 liter = liter->next;
177177 }
178178 iter = iter->next;
271271 ohcount_sourcefile_list_add_directory(list, argv[i]);
272272 closedir(dir);
273273 } else {
274 FILE *f = fopen(argv[i], "r");
274 FILE *f = fopen(argv[i], "rb");
275275 if (f) {
276276 ohcount_sourcefile_list_add_file(list, argv[i]);
277277 fclose(f);
6363 * @li Ragel 6.3 or later - http://research.cs.queensu.ca/~thurston/ragel/
6464 * @li GNU gperf - http://www.gnu.org/software/gperf/
6565 * @li PCRE - http://pcre.sourceforge.net/
66 * @li Bash - http://www.gnu.org/software/bash/
6667 *
6768 * Run the 'build' script to build Ohcount.
6869 *
8384 *
8485 * You may then link or copy 'ruby/ohcount.{rb,so}' and 'ruby/gestalt{/,.rb}'
8586 * to the appropriate places in your Ruby installation.
87 *
88 * Building the Doxygen docs requires:
89 *
90 * @li Doxygen - http://www.doxygen.org/
91 *
92 * @code
93 * $ cd doc
94 * $ Doxygen Doxyfile
95 * @endcode
8696 *
8797 * @section start First Steps
8898 *
123133 *
124134 * @section contact Contact Ohloh
125135 *
126 * For more information visit the Ohloh website: http://labs.ohloh.net
136 * For more information visit the Ohloh website: https://sourceforge.net/projects/ohcount
127137 *
128138 * You can reach Ohloh via email at: info@ohloh.net
129139 */
55 #include "sourcefile.h"
66 #include "log.h"
77 #include "hash/parser_hash.h"
8
9 struct ParserMap * ohcount_hash_parser_from_language (register const char *str, register unsigned int len);
810
911 int ohcount_parse(SourceFile *sourcefile, int count,
1012 void (*callback) (const char *, const char *, int, int,
274274 * input source file that goes in the 'test/src_dir/' and an expected output
275275 * file that goes in the 'test/expected_dir/' directory.
276276 *
277 * The header file will need to be "#include"ed in 'test/unit/test_parsers.h'.
277 * The header file will need to be "#include"ed in 'test/unit/parser_test.h'.
278278 * Then add the "all_[lang]_tests()" function to the "all_parser_tests()"
279279 * function.
280280 *
0 // ampl.rl written by Victor Zverovich. victor.zverovich@gmail.com
1
2 /************************* Required for every parser *************************/
3 #ifndef OHCOUNT_AMPL_PARSER_H
4 #define OHCOUNT_AMPL_PARSER_H
5
6 #include "../parser_macros.h"
7
8 // the name of the language
9 const char *AMPL_LANG = LANG_AMPL;
10
11 // the languages entities
12 const char *ampl_entities[] = {
13 "space", "comment", "any"
14 };
15
16 // constants associated with the entities
17 enum {
18 AMPL_SPACE = 0, AMPL_COMMENT, AMPL_ANY
19 };
20
21 /*****************************************************************************/
22
23 %%{
24 machine ampl;
25 write data;
26 include common "common.rl";
27
28 # Line counting machine
29
30 action ampl_ccallback {
31 switch(entity) {
32 case AMPL_SPACE:
33 ls
34 break;
35 case AMPL_ANY:
36 code
37 break;
38 case INTERNAL_NL:
39 std_internal_newline(AMPL_LANG)
40 break;
41 case NEWLINE:
42 std_newline(AMPL_LANG)
43 }
44 }
45
46 ampl_line_comment = '#' @comment nonnewline*;
47 ampl_block_comment =
48 '/*' @comment (
49 newline %{ entity = INTERNAL_NL; } %ampl_ccallback
50 |
51 ws
52 |
53 (nonnewline - ws) @comment
54 )* :>> '*/';
55 ampl_comment = ampl_line_comment | ampl_block_comment;
56
57 ampl_line := |*
58 spaces ${ entity = AMPL_SPACE; } => ampl_ccallback;
59 ampl_comment;
60 newline ${ entity = NEWLINE; } => ampl_ccallback;
61 ^space ${ entity = AMPL_ANY; } => ampl_ccallback;
62 *|;
63
64 # Entity machine
65
66 action ampl_ecallback {
67 callback(AMPL_LANG, ampl_entities[entity], cint(ts), cint(te), userdata);
68 }
69
70 ampl_line_comment_entity = '#' nonnewline*;
71 ampl_block_comment_entity = '/*' any* :>> '*/';
72 ampl_comment_entity =
73 ampl_line_comment_entity | ampl_block_comment_entity;
74
75 ampl_entity := |*
76 space+ ${ entity = AMPL_SPACE; } => ampl_ecallback;
77 ampl_comment_entity ${ entity = AMPL_COMMENT; } => ampl_ecallback;
78 ^space;
79 *|;
80 }%%
81
82 /************************* Required for every parser *************************/
83
84 /* Parses a string buffer with AMPL code.
85 *
86 * @param *buffer The string to parse.
87 * @param length The length of the string to parse.
88 * @param count Integer flag specifying whether or not to count lines. If yes,
89 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
90 * machine optimized for returning entity positions.
91 * @param *callback Callback function. If count is set, callback is called for
92 * every line of code, comment, or blank with 'lcode', 'lcomment', and
93 * 'lblank' respectively. Otherwise callback is called for each entity found.
94 */
95 void parse_ampl(char *buffer, int length, int count,
96 void (*callback) (const char *lang, const char *entity, int s,
97 int e, void *udata),
98 void *userdata
99 ) {
100 init
101
102 %% write init;
103 cs = (count) ? ampl_en_ampl_line : ampl_en_ampl_entity;
104 %% write exec;
105
106 // if no newline at EOF; callback contents of last line
107 if (count) { process_last_line(AMPL_LANG) }
108 }
109
110 #endif
111
112 /*****************************************************************************/
0 // augeas.rl, based on ocaml.rl
1 /************************* Required for every parser *************************/
2 #ifndef OHCOUNT_AUGEAS_PARSER_H
3 #define OHCOUNT_AUGEAS_PARSER_H
4
5 #include "../parser_macros.h"
6
7 // the name of the language
8 const char *AUGEAS_LANG = LANG_AUGEAS;
9
10 // the languages entities
11 const char *augeas_entities[] = {
12 "space", "comment", "string", "any"
13 };
14
15 // constants associated with the entities
16 enum {
17 AUGEAS_SPACE = 0, AUGEAS_COMMENT, AUGEAS_STRING, AUGEAS_ANY
18 };
19
20 /*****************************************************************************/
21
22 %%{
23 machine augeas;
24 write data;
25 include common "common.rl";
26
27 # Line counting machine
28
29 action augeas_ccallback {
30 switch(entity) {
31 case AUGEAS_SPACE:
32 ls
33 break;
34 case AUGEAS_ANY:
35 code
36 break;
37 case INTERNAL_NL:
38 std_internal_newline(AUGEAS_LANG)
39 break;
40 case NEWLINE:
41 std_newline(AUGEAS_LANG)
42 }
43 }
44
45 action augeas_comment_nc_res { nest_count = 0; }
46 action augeas_comment_nc_inc { nest_count++; }
47 action augeas_comment_nc_dec { nest_count--; }
48
49 augeas_nested_block_comment =
50 '(*' >augeas_comment_nc_res @comment (
51 newline %{ entity = INTERNAL_NL; } %augeas_ccallback
52 |
53 ws
54 |
55 '(*' @augeas_comment_nc_inc @comment
56 |
57 '*)' @augeas_comment_nc_dec @comment
58 |
59 (nonnewline - ws) @comment
60 )* :>> ('*)' when { nest_count == 0 }) @comment;
61
62 augeas_comment = augeas_nested_block_comment;
63 augeas_string = '"' @code ([^\r\n\f"\\] | '\\' nonnewline)* '"';
64
65
66 augeas_line := |*
67 spaces ${ entity = AUGEAS_SPACE; } => augeas_ccallback;
68 augeas_comment;
69 augeas_string;
70 newline ${ entity = NEWLINE; } => augeas_ccallback;
71 ^space ${ entity = AUGEAS_ANY; } => augeas_ccallback;
72 *|;
73
74 # Entity machine
75
76 action augeas_ecallback {
77 callback(AUGEAS_LANG, augeas_entities[entity], cint(ts), cint(te), userdata);
78 }
79
80 augeas_comment_entity = '(*' >augeas_comment_nc_res (
81 '(*' @augeas_comment_nc_inc
82 |
83 '*)' @augeas_comment_nc_dec
84 |
85 any
86 )* :>> ('*)' when { nest_count == 0 });
87
88 augeas_entity := |*
89 space+ ${ entity = AUGEAS_SPACE; } => augeas_ecallback;
90 augeas_comment_entity ${ entity = AUGEAS_COMMENT; } => augeas_ecallback;
91 # TODO:
92 ^space;
93 *|;
94 }%%
95
96 /************************* Required for every parser *************************/
97
98 /* Parses a string buffer with Objective Caml code.
99 *
100 * @param *buffer The string to parse.
101 * @param length The length of the string to parse.
102 * @param count Integer flag specifying whether or not to count lines. If yes,
103 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
104 * machine optimized for returning entity positions.
105 * @param *callback Callback function. If count is set, callback is called for
106 * every line of code, comment, or blank with 'lcode', 'lcomment', and
107 * 'lblank' respectively. Otherwise callback is called for each entity found.
108 */
109 void parse_augeas(char *buffer, int length, int count,
110 void (*callback) (const char *lang, const char *entity, int s,
111 int e, void *udata),
112 void *userdata
113 ) {
114 init
115
116 int nest_count = 0;
117
118 %% write init;
119 cs = (count) ? augeas_en_augeas_line : augeas_en_augeas_entity;
120 %% write exec;
121
122 // if no newline at EOF; callback contents of last line
123 if (count) { process_last_line(AUGEAS_LANG) }
124 }
125
126 #endif
127
128 /*****************************************************************************/
4343 }
4444 }
4545
46 bat_comment = /rem/i @comment nonnewline*;
46 bat_comment = ( /rem/i | /@rem/i | '::' ) @comment nonnewline*;
4747
4848 bat_line := |*
4949 spaces ${ entity = BAT_SPACE; } => bat_ccallback;
5858 callback(BAT_LANG, bat_entities[entity], cint(ts), cint(te), userdata);
5959 }
6060
61 bat_comment_entity = /rem/i nonnewline*;
61 bat_comment_entity = ( /rem/i | /@rem/i | '::' ) nonnewline*;
6262
6363 bat_entity := |*
6464 space+ ${ entity = BAT_SPACE; } => bat_ecallback;
0 // bfpp.rl written by Boris 'billiob' Faure billiob<att>gmail<dott>com
1
2 /************************* Required for every parser *************************/
3 #ifndef OHCOUNT_BFPP_PARSER_H
4 #define OHCOUNT_BFPP_PARSER_H
5
6 #include "../parser_macros.h"
7
8 // the name of the language
9 const char *BFPP_LANG = LANG_BFPP;
10
11 // the languages entities
12 const char *bfpp_entities[] = {
13 "space", "comment", "operator", "include"
14 };
15
16 // constants associated with the entities
17 enum {
18 BFPP_SPACE = 0, BFPP_COMMENT, BFPP_OPERATOR, BFPP_INCLUDE
19 };
20
21 /*****************************************************************************/
22
23 %%{
24 machine bfpp;
25 write data;
26 include common "common.rl";
27
28 # Line counting machine
29
30 action bfpp_ccallback {
31 switch(entity) {
32 case BFPP_SPACE:
33 ls
34 break;
35 case BFPP_OPERATOR:
36 case BFPP_INCLUDE:
37 code
38 break;
39 case BFPP_COMMENT:
40 comment
41 break;
42 case INTERNAL_NL:
43 std_internal_newline(BFPP_LANG)
44 break;
45 case NEWLINE:
46 std_newline(BFPP_LANG)
47 }
48 }
49
50 bfpp_operator = [+\-<>.,\[\]\%\!\#\^\:\;] @code;
51
52 bfpp_line_comment = ('=') @comment nonnewline*;
53
54 bfpp_include = '@include(' @code (
55 newline %{ entity = INTERNAL_NL; } %bfpp_ccallback
56 |
57 ws
58 |
59 (nonnewline - ws) @code
60 )* :>> ')';
61
62 bfpp_line := |*
63 spaces ${ entity = BFPP_SPACE; } => bfpp_ccallback;
64 newline ${ entity = NEWLINE; } => bfpp_ccallback;
65 bfpp_line_comment;
66 bfpp_include;
67 bfpp_operator ${ entity = BFPP_OPERATOR; } => bfpp_ccallback;
68 ^space ${ entity = BFPP_COMMENT; } => bfpp_ccallback;
69 *|;
70
71 # Entity machine
72
73 action bfpp_ecallback {
74 callback(BFPP_LANG, bfpp_entities[entity], cint(ts), cint(te), userdata);
75 }
76
77 bfpp_operator_entity = [+\-<>.,\[\]%\#^;:];
78
79 bfpp_include_entity = '@include(' any* :>> ')';
80
81 bfpp_line_comment_entity = '=' (escaped_newline | nonnewline)*;
82
83 bfpp_comment_entity = (bfpp_line_comment_entity |
84 !(space | bfpp_operator_entity | bfpp_include_entity));
85
86 bfpp_entity := |*
87 space+ ${ entity = BFPP_SPACE; } => bfpp_ecallback;
88 bfpp_operator_entity ${ entity = BFPP_OPERATOR; } => bfpp_ecallback;
89 bfpp_include_entity ${ entity = BFPP_INCLUDE; } => bfpp_ecallback;
90 bfpp_comment_entity ${ entity = BFPP_COMMENT; } => bfpp_ecallback;
91 *|;
92 }%%
93
94 /************************* Required for every parser *************************/
95
96 /* Parses a string buffer with Brainfuck++ code.
97 *
98 * @param *buffer The string to parse.
99 * @param length The length of the string to parse.
100 * @param count Integer flag specifying whether or not to count lines. If yes,
101 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
102 * machine optimized for returning entity positions.
103 * @param *callback Callback function. If count is set, callback is called for
104 * every line of code, comment, or blank with 'lcode', 'lcomment', and
105 * 'lblank' respectively. Otherwise callback is called for each entity found.
106 */
107 void parse_bfpp(char *buffer, int length, int count,
108 void (*callback) (const char *lang, const char *entity, int s,
109 int e, void *udata),
110 void *userdata
111 ) {
112 init
113
114 %% write init;
115 cs = (count) ? bfpp_en_bfpp_line : bfpp_en_bfpp_entity;
116 %% write exec;
117
118 // if no newline at EOF; callback contents of last line
119 if (count) { process_last_line(BFPP_LANG) }
120 }
121
122 #endif
123
124 /*****************************************************************************/
125
0 // brainfuck.rl written by Boris 'billiob' Faure billiob<att>gmail<dott>com
1
2 /************************* Required for every parser *************************/
3 #ifndef OHCOUNT_BRAINFUCK_PARSER_H
4 #define OHCOUNT_BRAINFUCK_PARSER_H
5
6 #include "../parser_macros.h"
7
8 // the name of the language
9 const char *BRAINFUCK_LANG = LANG_BRAINFUCK;
10
11 // the languages entities
12 const char *brainfuck_entities[] = {
13 "space", "comment", "operator"
14 };
15
16 // constants associated with the entities
17 enum {
18 BRAINFUCK_SPACE = 0, BRAINFUCK_COMMENT, BRAINFUCK_OPERATOR
19 };
20
21 /*****************************************************************************/
22
23 %%{
24 machine brainfuck;
25 write data;
26 include common "common.rl";
27
28 # Line counting machine
29
30 action brainfuck_ccallback {
31 switch(entity) {
32 case BRAINFUCK_SPACE:
33 ls
34 break;
35 case BRAINFUCK_OPERATOR:
36 code
37 break;
38 case BRAINFUCK_COMMENT:
39 comment
40 break;
41 case INTERNAL_NL:
42 std_internal_newline(BRAINFUCK_LANG)
43 break;
44 case NEWLINE:
45 std_newline(BRAINFUCK_LANG)
46 }
47 }
48
49 brainfuck_operator = [+\-<>.,\[\]] @code;
50
51 brainfuck_line := |*
52 spaces ${ entity = BRAINFUCK_SPACE; } => brainfuck_ccallback;
53 newline ${ entity = NEWLINE; } => brainfuck_ccallback;
54 brainfuck_operator ${ entity = BRAINFUCK_OPERATOR; } => brainfuck_ccallback;
55 ^space ${ entity = BRAINFUCK_COMMENT; } => brainfuck_ccallback;
56 *|;
57
58 # Entity machine
59
60 action brainfuck_ecallback {
61 callback(BRAINFUCK_LANG, brainfuck_entities[entity], cint(ts), cint(te), userdata);
62 }
63
64 brainfuck_operator_entity = [+\-<>.,\[\]];
65
66 brainfuck_comment_entity = !(space | brainfuck_operator_entity);
67
68 brainfuck_entity := |*
69 space+ ${ entity = BRAINFUCK_SPACE; } => brainfuck_ecallback;
70 brainfuck_operator_entity ${ entity = BRAINFUCK_OPERATOR; } => brainfuck_ecallback;
71 brainfuck_comment_entity ${ entity = BRAINFUCK_COMMENT; } => brainfuck_ecallback;
72 *|;
73 }%%
74
75 /************************* Required for every parser *************************/
76
77 /* Parses a string buffer with Brainfuck code.
78 *
79 * @param *buffer The string to parse.
80 * @param length The length of the string to parse.
81 * @param count Integer flag specifying whether or not to count lines. If yes,
82 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
83 * machine optimized for returning entity positions.
84 * @param *callback Callback function. If count is set, callback is called for
85 * every line of code, comment, or blank with 'lcode', 'lcomment', and
86 * 'lblank' respectively. Otherwise callback is called for each entity found.
87 */
88 void parse_brainfuck(char *buffer, int length, int count,
89 void (*callback) (const char *lang, const char *entity, int s,
90 int e, void *udata),
91 void *userdata
92 ) {
93 init
94
95 %% write init;
96 cs = (count) ? brainfuck_en_brainfuck_line : brainfuck_en_brainfuck_entity;
97 %% write exec;
98
99 // if no newline at EOF; callback contents of last line
100 if (count) { process_last_line(BRAINFUCK_LANG) }
101 }
102
103 #endif
104
105 /*****************************************************************************/
106
210210 C_LANG = ORIG_C_LANG;
211211 }
212212
213 const char *GENIE_LANG = LANG_GENIE;
214 void parse_genie(char *buffer, int length, int count,
215 void (*callback) (const char *lang, const char *entity,
216 int s, int e, void *udata),
217 void *userdata
218 ) {
219 C_LANG = GENIE_LANG;
220 parse_c(buffer, length, count, callback, userdata);
221 C_LANG = ORIG_C_LANG;
222 }
223
224 const char *CUDA_LANG = LANG_CUDA;
225 void parse_cuda(char *buffer, int length, int count,
226 void (*callback) (const char *lang, const char *entity, int s,
227 int e, void *udata),
228 void *userdata
229 ) {
230 C_LANG = CUDA_LANG;
231 parse_c(buffer, length, count, callback, userdata);
232 C_LANG = ORIG_C_LANG;
233 }
234
235 const char *EC_LANG = LANG_EC;
236 void parse_ec(char *buffer, int length, int count,
237 void (*callback) (const char *lang, const char *entity, int s,
238 int e, void *udata),
239 void *userdata
240 ) {
241 C_LANG = EC_LANG;
242 parse_c(buffer, length, count, callback, userdata);
243 C_LANG = ORIG_C_LANG;
244 }
245
213246 #endif
214247
215248 /*****************************************************************************/
0 // Chaiscript.rl written by Jason Turner. lefticus<att>gmail<dott>com
1 // based on Javascript.rl written by Mitchell Foral. mitchell<att>caladbolg<dott>net.
2
3 /************************* Required for every parser *************************/
4 #ifndef OHCOUNT_CHAISCRIPT_PARSER_H
5 #define OHCOUNT_CHAISCRIPT_PARSER_H
6
7 #include "../parser_macros.h"
8
9 // the name of the language
10 const char *CHAI_LANG = LANG_CHAISCRIPT;
11
12 // the languages entities
13 const char *chai_entities[] = {
14 "space", "comment", "string", "number", "keyword",
15 "identifier", "operator", "any"
16 };
17
18 // constants associated with the entities
19 enum {
20 CHAI_SPACE = 0, CHAI_COMMENT, CHAI_STRING, CHAI_NUMBER, CHAI_KEYWORD,
21 CHAI_IDENTIFIER, CHAI_OPERATOR, CHAI_ANY
22 };
23
24 /*****************************************************************************/
25
26 %%{
27 machine chaiscript;
28 write data;
29 include common "common.rl";
30
31 # Line counting machine
32
33 action chai_ccallback {
34 switch(entity) {
35 case CHAI_SPACE:
36 ls
37 break;
38 case CHAI_ANY:
39 code
40 break;
41 case INTERNAL_NL:
42 std_internal_newline(CHAI_LANG)
43 break;
44 case NEWLINE:
45 std_newline(CHAI_LANG)
46 }
47 }
48
49 chai_line_comment = '//' @comment nonnewline*;
50 chai_block_comment =
51 '/*' @comment (
52 newline %{ entity = INTERNAL_NL; } %chai_ccallback
53 |
54 ws
55 |
56 (nonnewline - ws) @comment
57 )* :>> '*/';
58 chai_comment = chai_line_comment | chai_block_comment;
59
60 # Does Javascript allow newlines inside strings?
61 # I can't find a definitive answer.
62 chai_sq_str =
63 '\'' @code (
64 escaped_newline %{ entity = INTERNAL_NL; } %chai_ccallback
65 |
66 ws
67 |
68 [^\t '\\] @code
69 |
70 '\\' nonnewline @code
71 )* '\'';
72 chai_dq_str =
73 '"' @code (
74 escaped_newline %{ entity = INTERNAL_NL; } %chai_ccallback
75 |
76 ws
77 |
78 [^\t "\\] @code
79 |
80 '\\' nonnewline @code
81 )* '"';
82 chai_regex_str = '/' [^/*] ([^\r\n\f/\\] | '\\' nonnewline)* '/' @code;
83 chai_string = chai_sq_str | chai_dq_str | chai_regex_str;
84
85 chai_line := |*
86 spaces ${ entity = CHAI_SPACE; } => chai_ccallback;
87 chai_comment;
88 chai_string;
89 newline ${ entity = NEWLINE; } => chai_ccallback;
90 ^space ${ entity = CHAI_ANY; } => chai_ccallback;
91 *|;
92
93 # Entity machine
94
95 action chai_ecallback {
96 callback(CHAI_LANG, chai_entities[entity], cint(ts), cint(te), userdata);
97 }
98
99 chai_line_comment_entity = '//' nonnewline*;
100 chai_block_comment_entity = '/*' any* :>> '*/';
101 chai_comment_entity = chai_line_comment_entity | chai_block_comment_entity;
102
103 chai_entity := |*
104 space+ ${ entity = CHAI_SPACE; } => chai_ecallback;
105 chai_comment_entity ${ entity = CHAI_COMMENT; } => chai_ecallback;
106 # TODO:
107 ^space;
108 *|;
109 }%%
110
111 /* Parses a string buffer with Chaiscript code.
112 *
113 * @param *buffer The string to parse.
114 * @param length The length of the string to parse.
115 * @param count Integer flag specifying whether or not to count lines. If yes,
116 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
117 * machine optimized for returning entity positions.
118 * @param *callback Callback function. If count is set, callback is called for
119 * every line of code, comment, or blank with 'lcode', 'lcomment', and
120 * 'lblank' respectively. Otherwise callback is called for each entity found.
121 */
122 void parse_chaiscript(char *buffer, int length, int count,
123 void (*callback) (const char *lang, const char *entity,
124 int s, int e, void *udata),
125 void *userdata
126 ) {
127 init
128
129 %% write init;
130 cs = (count) ? chaiscript_en_chai_line : chaiscript_en_chai_entity;
131 %% write exec;
132
133 // if no newline at EOF; callback contents of last line
134 if (count) { process_last_line(CHAI_LANG) }
135 }
136
137 #endif
0 /************************* Required for every parser *************************/
1 #ifndef OHCOUNT_COFFEESCRIPT_PARSER_H
2 #define OHCOUNT_COFFEESCRIPT_PARSER_H
3
4 #include "../parser_macros.h"
5
6 // the name of the language
7 const char *COFFEESCRIPT_LANG = LANG_COFFEESCRIPT;
8
9 // the languages entities
10 const char *coffeescript_entities[] = {
11 "space", "comment", "string", "any"
12 };
13
14 // constants associated with the entities
15 enum {
16 COFFEESCRIPT_SPACE = 0, COFFEESCRIPT_COMMENT, COFFEESCRIPT_STRING, COFFEESCRIPT_ANY
17 };
18
19 /*****************************************************************************/
20
21 #include "javascript.h"
22
23 %%{
24 machine coffeescript;
25 write data;
26 include common "common.rl";
27 #EMBED(javascript)
28
29 # Line counting machine
30
31 action coffeescript_ccallback {
32 switch(entity) {
33 case COFFEESCRIPT_SPACE:
34 ls
35 break;
36 case COFFEESCRIPT_ANY:
37 code
38 break;
39 case INTERNAL_NL:
40 std_internal_newline(COFFEESCRIPT_LANG)
41 break;
42 case NEWLINE:
43 std_newline(COFFEESCRIPT_LANG)
44 }
45 }
46
47 coffeescript_line_comment = ('#') @comment nonnewline*;
48 coffeescript_block_comment =
49 '###' @comment (
50 newline %{ entity = INTERNAL_NL; } %coffeescript_ccallback
51 |
52 ws
53 |
54 (nonnewline - ws) @comment
55 )* :>> '###';
56 coffeescript_comment = coffeescript_line_comment | coffeescript_block_comment;
57
58 coffeescript_sq_str =
59 '\'' @enqueue @code (
60 newline %{ entity = INTERNAL_NL; } %coffeescript_ccallback
61 |
62 ws
63 |
64 [^\r\n\f\t '\\] @code
65 |
66 '\\' nonnewline @code
67 )* '\'' @commit @code;
68 coffeescript_dq_str =
69 '"' @enqueue @code (
70 newline %{ entity = INTERNAL_NL; } %coffeescript_ccallback
71 |
72 ws
73 |
74 [^\r\n\f\t "\\] @code
75 |
76 '\\' nonnewline @code
77 )* '"' @commit @code;
78 coffeescript_sq_here_doc =
79 '\'\'\'' @code (
80 newline %{ entity = INTERNAL_NL; } %coffeescript_ccallback
81 |
82 ws
83 |
84 (nonnewline - ws) @code
85 )* :>> '\'\'\'' @code;
86 coffeescript_dq_here_doc =
87 '"""' @code (
88 newline %{ entity = INTERNAL_NL; } %coffeescript_ccallback
89 |
90 ws
91 |
92 (nonnewline - ws) @code
93 )* :>> '"""' @code;
94 coffeescript_string = (coffeescript_sq_str | coffeescript_dq_str |
95 coffeescript_sq_here_doc | coffeescript_dq_here_doc) @code;
96
97 coffeescript_js_entry = '`' @code;
98 coffeescript_js_outry = '`' @check_blank_outry @code;
99 coffeescript_js_line := |*
100 coffeescript_js_outry @{ p = ts; fret; };
101 # unmodified JavaScript patterns
102 spaces ${ entity = JS_SPACE; } => js_ccallback;
103 js_comment;
104 js_string;
105 newline ${ entity = NEWLINE; } => js_ccallback;
106 ^space ${ entity = JS_ANY; } => js_ccallback;
107 *|;
108
109 coffeescript_line := |*
110 coffeescript_js_entry @coffeescript_ccallback
111 @{ saw(JS_LANG); } => { fcall coffeescript_js_line; };
112 spaces ${ entity = COFFEESCRIPT_SPACE; } => coffeescript_ccallback;
113 coffeescript_comment;
114 coffeescript_string;
115 newline ${ entity = NEWLINE; } => coffeescript_ccallback;
116 ^space ${ entity = COFFEESCRIPT_ANY; } => coffeescript_ccallback;
117 *|;
118
119 # Entity machine
120
121 action coffeescript_ecallback {
122 callback(COFFEESCRIPT_LANG, coffeescript_entities[entity], cint(ts), cint(te),
123 userdata);
124 }
125
126 coffeescript_line_comment_entity = ('#') nonnewline*;
127 coffeescript_block_comment_entity = '###' any* :>> '###';
128 coffeescript_comment_entity = coffeescript_line_comment_entity |
129 coffeescript_block_comment_entity;
130
131 coffeescript_entity := |*
132 space+ ${ entity = COFFEESCRIPT_SPACE; } => coffeescript_ecallback;
133 coffeescript_comment_entity ${ entity = COFFEESCRIPT_COMMENT; } => coffeescript_ecallback;
134 # TODO:
135 ^space;
136 *|;
137 }%%
138
139 /************************* Required for every parser *************************/
140
141 /* Parses a string buffer with CoffeeScript code.
142 *
143 * @param *buffer The string to parse.
144 * @param length The length of the string to parse.
145 * @param count Integer flag specifying whether or not to count lines. If yes,
146 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
147 * machine optimized for returning entity positions.
148 * @param *callback Callback function. If count is set, callback is called for
149 * every line of code, comment, or blank with 'lcode', 'lcomment', and
150 * 'lblank' respectively. Otherwise callback is called for each entity found.
151 */
152 void parse_coffeescript(char *buffer, int length, int count,
153 void (*callback) (const char *lang, const char *entity, int s,
154 int e, void *udata),
155 void *userdata
156 ) {
157 init
158
159 %% write init;
160 cs = (count) ? coffeescript_en_coffeescript_line : coffeescript_en_coffeescript_entity;
161 %% write exec;
162
163 // if no newline at EOF; callback contents of last line
164 if (count) { process_last_line(COFFEESCRIPT_LANG) }
165 }
166
167 #endif
168
169 /*****************************************************************************/
00 #!/bin/sh
11 # Compiles all .rl files for Ohcount.
22 # Written by Mitchell Foral. mitchell<att>caladbolg<dott>net.
3
4 # check to make sure we have ragel
5 if `type ragel > /dev/null 2> /dev/null`
6 then
7 echo "Found ragel, compiling..."
8 else
9 echo "ragel not found, aborting" >&2
10 exit 1
11 fi
312
413 for file in *.rl
514 do
0 /************************* Required for every parser *************************/
1 #ifndef OHCOUNT_COQ_PARSER_H
2 #define OHCOUNT_COQ_PARSER_H
3
4 #include "../parser_macros.h"
5
6 // the name of the language
7 const char *COQ_LANG = LANG_COQ;
8
9 // the languages entities
10 const char *coq_entities[] = {
11 "space", "comment", "string", "any"
12 };
13
14 // constants associated with the entities
15 enum {
16 COQ_SPACE = 0, COQ_COMMENT, COQ_STRING, COQ_ANY
17 };
18
19 /*****************************************************************************/
20
21 %%{
22 machine coq;
23 write data;
24 include common "common.rl";
25
26 # Line counting machine
27
28 action coq_ccallback {
29 switch(entity) {
30 case COQ_SPACE:
31 ls
32 break;
33 case COQ_ANY:
34 code
35 break;
36 case INTERNAL_NL:
37 std_internal_newline(COQ_LANG)
38 break;
39 case NEWLINE:
40 std_newline(COQ_LANG)
41 }
42 }
43
44 action coq_comment_nc_res { nest_count = 0; }
45 action coq_comment_nc_inc { nest_count++; }
46 action coq_comment_nc_dec { nest_count--; }
47
48 coq_nested_block_comment =
49 '(*' >coq_comment_nc_res @comment (
50 newline %{ entity = INTERNAL_NL; } %coq_ccallback
51 |
52 ws
53 |
54 '(*' @coq_comment_nc_inc @comment
55 |
56 '*)' @coq_comment_nc_dec @comment
57 |
58 (nonnewline - ws) @comment
59 )* :>> ('*)' when { nest_count == 0 }) @comment;
60
61 coq_comment = coq_nested_block_comment;
62
63 coq_string =
64 '"' @code (
65 newline %{ entity = INTERNAL_NL; } %coq_ccallback
66 |
67 ws
68 |
69 [^"] @code
70 )* '"';
71
72 coq_line := |*
73 spaces ${ entity = COQ_SPACE; } => coq_ccallback;
74 coq_comment;
75 coq_string;
76 newline ${ entity = NEWLINE; } => coq_ccallback;
77 ^space ${ entity = COQ_ANY; } => coq_ccallback;
78 *|;
79
80 # Entity machine
81
82 action coq_ecallback {
83 callback(COQ_LANG, coq_entities[entity], cint(ts), cint(te), userdata);
84 }
85
86 coq_comment_entity = '(*' >coq_comment_nc_res (
87 '(*' @coq_comment_nc_inc
88 |
89 '*)' @coq_comment_nc_dec
90 |
91 any
92 )* :>> ('*)' when { nest_count == 0 });
93
94 coq_entity := |*
95 space+ ${ entity = COQ_SPACE; } => coq_ecallback;
96 coq_comment_entity ${ entity = COQ_COMMENT; } => coq_ecallback;
97 # TODO:
98 ^space;
99 *|;
100 }%%
101
102 /************************* Required for every parser *************************/
103
104 /* Parses a string buffer with Coq code.
105 *
106 * @param *buffer The string to parse.
107 * @param length The length of the string to parse.
108 * @param count Integer flag specifying whether or not to count lines. If yes,
109 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
110 * machine optimized for returning entity positions.
111 * @param *callback Callback function. If count is set, callback is called for
112 * every line of code, comment, or blank with 'lcode', 'lcomment', and
113 * 'lblank' respectively. Otherwise callback is called for each entity found.
114 */
115 void parse_coq(char *buffer, int length, int count,
116 void (*callback) (const char *lang, const char *entity, int s,
117 int e, void *udata),
118 void *userdata
119 ) {
120 init
121
122 int nest_count = 0;
123
124 %% write init;
125 cs = (count) ? coq_en_coq_line : coq_en_coq_entity;
126 %% write exec;
127
128 // if no newline at EOF; callback contents of last line
129 if (count) { process_last_line(COQ_LANG) }
130 }
131
132 #endif
133
134 /*****************************************************************************/
0 // forth.rl
1 // derived from code written by Mitchell Foral. mitchell<att>caladbolg<dott>net.
2
3 /************************* Required for every parser *************************/
4 #ifndef OHCOUNT_FORTH_PARSER_H
5 #define OHCOUNT_FORTH_PARSER_H
6
7 #include "../parser_macros.h"
8
9 // the name of the language
10 const char *FORTH_LANG = LANG_FORTH;
11
12 // the languages entities
13 const char *forth_entities[] = {
14 "space", "comment", "string", "any",
15 };
16
17 // constants associated with the entities
18 enum {
19 FORTH_SPACE = 0, FORTH_COMMENT, FORTH_STRING, FORTH_ANY
20 };
21
22 /*****************************************************************************/
23
24 %%{
25 machine forth;
26 write data;
27 include common "common.rl";
28
29 # Line counting machine
30
31 action forth_ccallback {
32 switch(entity) {
33 case FORTH_SPACE:
34 ls
35 break;
36 case FORTH_ANY:
37 code
38 break;
39 case INTERNAL_NL:
40 std_internal_newline(FORTH_LANG)
41 break;
42 case NEWLINE:
43 std_newline(FORTH_LANG)
44 }
45 }
46
47 forth_line_comment = '\\' @comment nonnewline*;
48 forth_block_comment =
49 '(' @comment (
50 newline %{ entity = INTERNAL_NL; } %forth_ccallback
51 |
52 ws
53 |
54 (nonnewline - ws) @comment
55 )* :>> ')';
56 forth_comment = forth_line_comment | forth_block_comment;
57
58 forth_string = '"' @code ([^\r\n\f"])* '"';
59
60 forth_line := |*
61 spaces ${ entity = FORTH_SPACE; } => forth_ccallback;
62 forth_comment;
63 forth_string;
64 newline ${ entity = NEWLINE; } => forth_ccallback;
65 ^space ${ entity = FORTH_ANY; } => forth_ccallback;
66 *|;
67
68 # Entity machine
69
70 action forth_ecallback {
71 callback(FORTH_LANG, forth_entities[entity], cint(ts), cint(te), userdata);
72 }
73
74 forth_line_comment_entity = '\\' nonnewline*;
75 forth_block_comment_entity = '(' any* :>> ')';
76 forth_comment_entity = forth_line_comment_entity | forth_block_comment_entity;
77
78 forth_entity := |*
79 space+ ${ entity = FORTH_SPACE; } => forth_ecallback;
80 forth_comment_entity ${ entity = FORTH_COMMENT; } => forth_ecallback;
81 # TODO:
82 ^space;
83 *|;
84 }%%
85
86 /************************* Required for every parser *************************/
87
88 /* Parses a string buffer with Forth code.
89 *
90 * @param *buffer The string to parse.
91 * @param length The length of the string to parse.
92 * @param count Integer flag specifying whether or not to count lines. If yes,
93 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
94 * machine optimized for returning entity positions.
95 * @param *callback Callback function. If count is set, callback is called for
96 * every line of code, comment, or blank with 'lcode', 'lcomment', and
97 * 'lblank' respectively. Otherwise callback is called for each entity found.
98 */
99 void parse_forth(char *buffer, int length, int count,
100 void (*callback) (const char *lang, const char *entity, int s,
101 int e, void *udata),
102 void *userdata
103 ) {
104 init
105
106 %% write init;
107 cs = (count) ? forth_en_forth_line : forth_en_forth_entity;
108 %% write exec;
109
110 // if no newline at EOF; callback contents of last line
111 if (count) { process_last_line(FORTH_LANG) }
112 }
113
114 #endif
115
116 /*****************************************************************************/
0 // golang.rl written by Scott Lawrence <bytbox@gmail.com>
1
2 /************************* Required for every parser *************************/
3 #ifndef OHCOUNT_GOLANG_PARSER_H
4 #define OHCOUNT_GOLANG_PARSER_H
5
6 #include "../parser_macros.h"
7
8 // the name of the language
9 const char *GOLANG_LANG = LANG_GOLANG;
10
11 // the languages entities
12 const char *golang_entities[] = {
13 "space", "comment", "string", "number", "preproc",
14 "keyword", "identifier", "operator", "any"
15 };
16
17 // constants associated with the entities
18 enum {
19 GOLANG_SPACE = 0, GOLANG_COMMENT, GOLANG_STRING, GOLANG_NUMBER, GOLANG_PREPROC,
20 GOLANG_KEYWORD, GOLANG_IDENTIFIER, GOLANG_OPERATOR, GOLANG_ANY
21 };
22
23 /*****************************************************************************/
24
25 %%{
26 machine golang;
27 write data;
28 include common "common.rl";
29
30 # Line counting machine
31
32 action golang_ccallback {
33 switch(entity) {
34 case GOLANG_SPACE:
35 ls
36 break;
37 case GOLANG_ANY:
38 code
39 break;
40 case INTERNAL_NL:
41 std_internal_newline(GOLANG_LANG)
42 break;
43 case NEWLINE:
44 std_newline(GOLANG_LANG)
45 }
46 }
47
48 golang_line_comment =
49 '//' @comment (
50 escaped_newline %{ entity = INTERNAL_NL; } %golang_ccallback
51 |
52 ws
53 |
54 (nonnewline - ws) @comment
55 )*;
56 golang_block_comment =
57 '/*' @comment (
58 newline %{ entity = INTERNAL_NL; } %golang_ccallback
59 |
60 ws
61 |
62 (nonnewline - ws) @comment
63 )* :>> '*/';
64 golang_comment = golang_line_comment | golang_block_comment;
65
66 golang_sq_str =
67 '\'' @code (
68 escaped_newline %{ entity = INTERNAL_NL; } %golang_ccallback
69 |
70 ws
71 |
72 [^\t '\\] @code
73 |
74 '\\' nonnewline @code
75 )* '\'';
76 golang_dq_str =
77 '"' @code (
78 escaped_newline %{ entity = INTERNAL_NL; } %golang_ccallback
79 |
80 ws
81 |
82 [^\t "\\] @code
83 |
84 '\\' nonnewline @code
85 )* '"';
86 golang_string = golang_sq_str | golang_dq_str;
87
88 golang_line := |*
89 spaces ${ entity = GOLANG_SPACE; } => golang_ccallback;
90 golang_comment;
91 golang_string;
92 newline ${ entity = NEWLINE; } => golang_ccallback;
93 ^space ${ entity = GOLANG_ANY; } => golang_ccallback;
94 *|;
95
96 # Entity machine
97
98 action golang_ecallback {
99 callback(GOLANG_LANG, golang_entities[entity], cint(ts), cint(te), userdata);
100 }
101
102 golang_line_comment_entity = '//' (escaped_newline | nonnewline)*;
103 golang_block_comment_entity = '/*' any* :>> '*/';
104 golang_comment_entity = golang_line_comment_entity | golang_block_comment_entity;
105
106 golang_string_entity = sq_str_with_escapes | dq_str_with_escapes;
107
108 golang_number_entity = float | integer;
109
110 golang_preprogolang_word =
111 'define' | 'elif' | 'else' | 'endif' | 'error' | 'if' | 'ifdef' |
112 'ifndef' | 'import' | 'include' | 'line' | 'pragma' | 'undef' |
113 'using' | 'warning';
114 # TODO: find some way of making preproc match the beginning of a line.
115 # Putting a 'when starts_line' conditional throws an assertion error.
116 golang_preprogolang_entity =
117 '#' space* (golang_block_comment_entity space*)?
118 golang_preprogolang_word (escaped_newline | nonnewline)*;
119
120 golang_identifier_entity = (alpha | '_') (alnum | '_')*;
121
122 golang_keyword_entity =
123 'and' | 'and_eq' | 'asm' | 'auto' | 'bitand' | 'bitor' | 'bool' |
124 'break' | 'case' | 'catch' | 'char' | 'class' | 'compl' | 'const' |
125 'const_cast' | 'continue' | 'default' | 'delete' | 'do' | 'double' |
126 'dynamigolang_cast' | 'else' | 'enum' | 'explicit' | 'export' | 'extern' |
127 'false' | 'float' | 'for' | 'friend' | 'goto' | 'if' | 'inline' | 'int' |
128 'long' | 'mutable' | 'namespace' | 'new' | 'not' | 'not_eq' |
129 'operator' | 'or' | 'or_eq' | 'private' | 'protected' | 'public' |
130 'register' | 'reinterpret_cast' | 'return' | 'short' | 'signed' |
131 'sizeof' | 'static' | 'statigolang_cast' | 'struct' | 'switch' |
132 'template' | 'this' | 'throw' | 'true' | 'try' | 'typedef' | 'typeid' |
133 'typename' | 'union' | 'unsigned' | 'using' | 'virtual' | 'void' |
134 'volatile' | 'wchar_t' | 'while' | 'xor' | 'xor_eq';
135
136 golang_operator_entity = [+\-/*%<>!=^&|?~:;.,()\[\]{}];
137
138 golang_entity := |*
139 space+ ${ entity = GOLANG_SPACE; } => golang_ecallback;
140 golang_comment_entity ${ entity = GOLANG_COMMENT; } => golang_ecallback;
141 golang_string_entity ${ entity = GOLANG_STRING; } => golang_ecallback;
142 golang_number_entity ${ entity = GOLANG_NUMBER; } => golang_ecallback;
143 golang_preprogolang_entity ${ entity = GOLANG_PREPROC; } => golang_ecallback;
144 golang_identifier_entity ${ entity = GOLANG_IDENTIFIER; } => golang_ecallback;
145 golang_keyword_entity ${ entity = GOLANG_KEYWORD; } => golang_ecallback;
146 golang_operator_entity ${ entity = GOLANG_OPERATOR; } => golang_ecallback;
147 ^(space | digit) ${ entity = GOLANG_ANY; } => golang_ecallback;
148 *|;
149 }%%
150
151 /************************* Required for every parser *************************/
152
153 /* Parses a string buffer with C/C++ code.
154 *
155 * @param *buffer The string to parse.
156 * @param length The length of the string to parse.
157 * @param count Integer flag specifying whether or not to count lines. If yes,
158 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
159 * machine optimized for returning entity positions.
160 * @param *callback Callback function. If count is set, callback is called for
161 * every line of code, comment, or blank with 'lcode', 'lcomment', and
162 * 'lblank' respectively. Otherwise callback is called for each entity found.
163 */
164 void parse_golang(char *buffer, int length, int count,
165 void (*callback) (const char *lang, const char *entity, int s,
166 int e, void *udata),
167 void *userdata
168 ) {
169 init
170
171 %% write init;
172 cs = (count) ? golang_en_golang_line : golang_en_golang_entity;
173 %% write exec;
174
175 // if no newline at EOF; callback contents of last line
176 if (count) { process_last_line(GOLANG_LANG) }
177 }
178
179 const char *ORIG_GOLANG_LANG = LANG_GOLANG;
180
181 #endif
182
183 /*****************************************************************************/
0 // grace.rl written by Michael Homer, based on shell.rl
1 // by Mitchell Foral. mitchell<att>caladbolg<dott>net
2
3 /************************* Required for every parser *************************/
4 #ifndef OHCOUNT_GRACE_PARSER_H
5 #define OHCOUNT_GRACE_PARSER_H
6
7 #include "../parser_macros.h"
8
9 // the name of the language
10 const char *GRACE_LANG = LANG_GRACE;
11
12 // the languages entities
13 const char *grace_entities[] = {
14 "space", "comment", "string", "any"
15 };
16
17 // constants associated with the entities
18 enum {
19 GRACE_SPACE = 0, GRACE_COMMENT, GRACE_STRING, GRACE_ANY
20 };
21
22 /*****************************************************************************/
23
24 %%{
25 machine grace;
26 write data;
27 include common "common.rl";
28
29 # Line counting machine
30
31 action grace_ccallback {
32 switch(entity) {
33 case GRACE_SPACE:
34 ls
35 break;
36 case GRACE_ANY:
37 code
38 break;
39 case INTERNAL_NL:
40 std_internal_newline(GRACE_LANG)
41 break;
42 case NEWLINE:
43 std_newline(GRACE_LANG)
44 }
45 }
46
47 grace_comment = '//' @comment nonnewline*;
48
49 grace_string =
50 '"' @enqueue @code (
51 newline %{ entity = INTERNAL_NL; } %grace_ccallback
52 |
53 ws
54 |
55 [^\r\n\f\t "\\] @code
56 )* '"' @commit;
57
58 grace_line := |*
59 spaces ${ entity = GRACE_SPACE; } => grace_ccallback;
60 grace_comment;
61 grace_string;
62 newline ${ entity = NEWLINE; } => grace_ccallback;
63 ^space ${ entity = GRACE_ANY; } => grace_ccallback;
64 *|;
65
66 # Entity machine
67
68 action grace_ecallback {
69 callback(GRACE_LANG, grace_entities[entity], cint(ts), cint(te), userdata);
70 }
71
72 grace_comment_entity = '//' nonnewline*;
73
74 grace_entity := |*
75 space+ ${ entity = GRACE_SPACE; } => grace_ecallback;
76 grace_comment_entity ${ entity = GRACE_COMMENT; } => grace_ecallback;
77 # TODO:
78 ^space;
79 *|;
80 }%%
81
82 /************************* Required for every parser *************************/
83
84 /* Parses a string buffer with Grace code.
85 *
86 * @param *buffer The string to parse.
87 * @param length The length of the string to parse.
88 * @param count Integer flag specifying whether or not to count lines. If yes,
89 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
90 * machine optimized for returning entity positions.
91 * @param *callback Callback function. If count is set, callback is called for
92 * every line of code, comment, or blank with 'lcode', 'lcomment', and
93 * 'lblank' respectively. Otherwise callback is called for each entity found.
94 */
95 void parse_grace(char *buffer, int length, int count,
96 void (*callback) (const char *lang, const char *entity, int s,
97 int e, void *udata),
98 void *userdata
99 ) {
100 init
101
102 %% write init;
103 cs = (count) ? grace_en_grace_line : grace_en_grace_entity;
104 %% write exec;
105
106 // if no newline at EOF; callback contents of last line
107 if (count) { process_last_line(GRACE_LANG) }
108 }
109
110 #endif
111
112 /*****************************************************************************/
0 // jam.rl written by Scott Lawrence. bytbox@gmail.com
1
2 /************************* Required for every parser *************************/
3 #ifndef OHCOUNT_JAM_PARSER_H
4 #define OHCOUNT_JAM_PARSER_H
5
6 #include "../parser_macros.h"
7
8 // the name of the language
9 const char *JAM_LANG = LANG_JAM;
10
11 // the languages entities
12 const char *jam_entities[] = {
13 "space", "comment", "string", "any"
14 };
15
16 // constants associated with the entities
17 enum {
18 JAM_SPACE = 0, JAM_COMMENT, JAM_STRING, JAM_ANY
19 };
20
21 /*****************************************************************************/
22
23 %%{
24 machine jam;
25 write data;
26 include common "common.rl";
27
28 # Line counting machine
29
30 action jam_ccallback {
31 switch(entity) {
32 case JAM_SPACE:
33 ls
34 break;
35 case JAM_ANY:
36 code
37 break;
38 case INTERNAL_NL:
39 std_internal_newline(JAM_LANG)
40 break;
41 case NEWLINE:
42 std_newline(JAM_LANG)
43 }
44 }
45
46 jam_comment = '#' @comment nonnewline*;
47
48 jam_sq_str =
49 '\'' @enqueue @code (
50 newline %{ entity = INTERNAL_NL; } %jam_ccallback
51 |
52 ws
53 |
54 [^\r\n\f\t '\\] @code
55 |
56 '\\' nonnewline @code
57 )* '\'' @commit;
58 jam_dq_str =
59 '"' @enqueue @code (
60 newline %{ entity = INTERNAL_NL; } %jam_ccallback
61 |
62 ws
63 |
64 [^\r\n\f\t "\\] @code
65 |
66 '\\' nonnewline @code
67 )* '"' @commit;
68 # TODO: heredocs; see ruby.rl for details
69 jam_string = jam_sq_str | jam_dq_str;
70
71 jam_line := |*
72 spaces ${ entity = JAM_SPACE; } => jam_ccallback;
73 jam_comment;
74 jam_string;
75 newline ${ entity = NEWLINE; } => jam_ccallback;
76 ^space ${ entity = JAM_ANY; } => jam_ccallback;
77 *|;
78
79 # Entity machine
80
81 action jam_ecallback {
82 callback(JAM_LANG, jam_entities[entity], cint(ts), cint(te), userdata);
83 }
84
85 jam_comment_entity = '#' nonnewline*;
86
87 jam_entity := |*
88 space+ ${ entity = JAM_SPACE; } => jam_ecallback;
89 jam_comment_entity ${ entity = JAM_COMMENT; } => jam_ecallback;
90 # TODO:
91 ^space;
92 *|;
93 }%%
94
95 /************************* Required for every parser *************************/
96
97 /* Parses a string buffer with Jam code.
98 *
99 * @param *buffer The string to parse.
100 * @param length The length of the string to parse.
101 * @param count Integer flag specifying whether or not to count lines. If yes,
102 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
103 * machine optimized for returning entity positions.
104 * @param *callback Callback function. If count is set, callback is called for
105 * every line of code, comment, or blank with 'lcode', 'lcomment', and
106 * 'lblank' respectively. Otherwise callback is called for each entity found.
107 */
108 void parse_jam(char *buffer, int length, int count,
109 void (*callback) (const char *lang, const char *entity, int s,
110 int e, void *udata),
111 void *userdata
112 ) {
113 init
114
115 %% write init;
116 cs = (count) ? jam_en_jam_line : jam_en_jam_entity;
117 %% write exec;
118
119 // if no newline at EOF; callback contents of last line
120 if (count) { process_last_line(JAM_LANG) }
121 }
122
123 #endif
124
125 /*****************************************************************************/
133133 if (count) { process_last_line(JS_LANG) }
134134 }
135135
136 const char *QML_LANG = LANG_QML;
137 const char *TS_LANG = LANG_TYPESCRIPT;
138 const char *ORIG_JS_LANG = LANG_JAVASCRIPT;
139
140 void parse_qml(char *buffer, int length, int count,
141 void (*callback) (const char *lang, const char *entity,
142 int s, int e, void *udata),
143 void *userdata
144 ) {
145 JS_LANG = QML_LANG;
146 parse_javascript(buffer, length, count, callback, userdata);
147 JS_LANG = ORIG_JS_LANG;
148 }
149
150 void parse_typescript(char *buffer, int length, int count,
151 void (*callback) (const char *lang, const char *entity,
152 int s, int e, void *udata),
153 void *userdata
154 ) {
155 JS_LANG = TS_LANG;
156 parse_javascript(buffer, length, count, callback, userdata);
157 JS_LANG = ORIG_JS_LANG;
158 }
159
136160 #endif
147147 LISP_LANG = ORIG_LISP_LANG;
148148 }
149149
150 const char *CLOJURE_LANG = LANG_CLOJURE;
151 void parse_clojure(char *buffer, int length, int count,
152 void (*callback) (const char *lang, const char *entity, int s,
153 int e, void *udata),
154 void *userdata
155 ) {
156 LISP_LANG = CLOJURE_LANG;
157 parse_lisp(buffer, length, count, callback, userdata);
158 LISP_LANG = ORIG_LISP_LANG;
159 }
160
161 const char *RACKET_LANG = LANG_RACKET;
162 void parse_racket(char *buffer, int length, int count,
163 void (*callback) (const char *lang, const char *entity, int s,
164 int e, void *udata),
165 void *userdata
166 ) {
167 LISP_LANG = RACKET_LANG;
168 parse_lisp(buffer, length, count, callback, userdata);
169 LISP_LANG = ORIG_LISP_LANG;
170 }
171
172
150173 #endif
0 // logtalk.rl written by Paulo Moura. pmoura<att>logtalk<dott>org.
1
2 /************************* Required for every parser *************************/
3 #ifndef OHCOUNT_LOGTALK_PARSER_H
4 #define OHCOUNT_LOGTALK_PARSER_H
5
6 #include "../parser_macros.h"
7
8 // the name of the language
9 const char *LOGTALK_LANG = LANG_LOGTALK;
10
11 // the languages entities
12 const char *logtalk_entities[] = {
13 "space", "comment", "string", "any"
14 };
15
16 // constants associated with the entities
17 enum {
18 LOGTALK_SPACE = 0, LOGTALK_COMMENT, LOGTALK_STRING, LOGTALK_ANY
19 };
20
21 /*****************************************************************************/
22
23 %%{
24 machine logtalk;
25 write data;
26 include common "common.rl";
27
28 # Line counting machine
29
30 action logtalk_ccallback {
31 switch(entity) {
32 case LOGTALK_SPACE:
33 ls
34 break;
35 case LOGTALK_ANY:
36 code
37 break;
38 case INTERNAL_NL:
39 std_internal_newline(LOGTALK_LANG)
40 break;
41 case NEWLINE:
42 std_newline(LOGTALK_LANG)
43 }
44 }
45
46 logtalk_line_comment = '%' @comment nonnewline*;
47 logtalk_block_comment =
48 '/*' @comment (
49 newline %{ entity = INTERNAL_NL; } %logtalk_ccallback
50 |
51 ws
52 |
53 (nonnewline - ws) @comment
54 )* :>> '*/';
55 logtalk_comment = logtalk_line_comment | logtalk_block_comment;
56
57 logtalk_sq_str = '\'' @code ([^\r\n\f'\\] | '\\' nonnewline)* '\'';
58 logtalk_dq_str = '"' @code ([^\r\n\f"\\] | '\\' nonnewline)* '"';
59 logtalk_string = logtalk_sq_str | logtalk_dq_str;
60
61 logtalk_line := |*
62 spaces ${ entity = LOGTALK_SPACE; } => logtalk_ccallback;
63 logtalk_comment;
64 logtalk_string;
65 newline ${ entity = NEWLINE; } => logtalk_ccallback;
66 ^space ${ entity = LOGTALK_ANY; } => logtalk_ccallback;
67 *|;
68
69 # Entity machine
70
71 action logtalk_ecallback {
72 callback(LOGTALK_LANG, logtalk_entities[entity], cint(ts), cint(te),
73 userdata);
74 }
75
76 logtalk_line_comment_entity = '%' nonnewline*;
77 logtalk_block_comment_entity = '/*' any* :>> '*/';
78 logtalk_comment_entity = logtalk_line_comment_entity | logtalk_block_comment_entity;
79
80 logtalk_entity := |*
81 space+ ${ entity = LOGTALK_SPACE; } => logtalk_ecallback;
82 logtalk_comment_entity ${ entity = LOGTALK_COMMENT; } => logtalk_ecallback;
83 # TODO:
84 ^space;
85 *|;
86 }%%
87
88 /************************* Required for every parser *************************/
89
90 /* Parses a string buffer with Logtalk code.
91 *
92 * @param *buffer The string to parse.
93 * @param length The length of the string to parse.
94 * @param count Integer flag specifying whether or not to count lines. If yes,
95 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
96 * machine optimized for returning entity positions.
97 * @param *callback Callback function. If count is set, callback is called for
98 * every line of code, comment, or blank with 'lcode', 'lcomment', and
99 * 'lblank' respectively. Otherwise callback is called for each entity found.
100 */
101 void parse_logtalk(char *buffer, int length, int count,
102 void (*callback) (const char *lang, const char *entity, int s,
103 int e, void *udata),
104 void *userdata
105 ) {
106 init
107
108 %% write init;
109 cs = (count) ? logtalk_en_logtalk_line : logtalk_en_logtalk_entity;
110 %% write exec;
111
112 // if no newline at EOF; callback contents of last line
113 if (count) { process_last_line(LOGTALK_LANG) }
114 }
115
116 #endif
117
118 /*****************************************************************************/
0 // mathematica.rl written by Erik Schnetter <eschnetter@perimaterinstitute.ca>
1
2 /************************* Required for every parser *************************/
3 #ifndef OHCOUNT_MATHEMATICA_PARSER_H
4 #define OHCOUNT_MATHEMATICA_PARSER_H
5
6 #include "../parser_macros.h"
7
8 // the name of the language
9 const char *MATHEMATICA_LANG = LANG_MATHEMATICA;
10
11 // the languages entities
12 const char *mathematica_entities[] = {
13 "space", "comment", "string", "any",
14 };
15
16 // constants associated with the entities
17 enum {
18 MATHEMATICA_SPACE = 0, MATHEMATICA_COMMENT, MATHEMATICA_STRING, MATHEMATICA_ANY
19 };
20
21 /*****************************************************************************/
22
23 %%{
24 machine mathematica;
25 write data;
26 include common "common.rl";
27
28 # Line counting machine
29
30 action mathematica_ccallback {
31 switch(entity) {
32 case MATHEMATICA_SPACE:
33 ls
34 break;
35 case MATHEMATICA_ANY:
36 code
37 break;
38 case INTERNAL_NL:
39 std_internal_newline(MATHEMATICA_LANG)
40 break;
41 case NEWLINE:
42 std_newline(MATHEMATICA_LANG)
43 }
44 }
45
46 action mathematica_comment_nc_res { nest_count = 0; }
47 action mathematica_comment_nc_inc { nest_count++; }
48 action mathematica_comment_nc_dec { nest_count--; }
49
50 mathematica_nested_block_comment =
51 '(*' >mathematica_comment_nc_res @comment (
52 newline %{ entity = INTERNAL_NL; } %mathematica_ccallback
53 |
54 ws
55 |
56 '(*' @mathematica_comment_nc_inc @comment
57 |
58 '*)' @mathematica_comment_nc_dec @comment
59 |
60 (nonnewline - ws) @comment
61 )* :>> ('*)' when { nest_count == 0 }) @comment;
62
63 mathematica_comment = mathematica_nested_block_comment;
64
65 mathematica_string = '"' @code ([^"]) '"';
66
67 mathematica_line := |*
68 spaces ${ entity = MATHEMATICA_SPACE; } => mathematica_ccallback;
69 mathematica_comment;
70 mathematica_string;
71 newline ${ entity = NEWLINE; } => mathematica_ccallback;
72 ^space ${ entity = MATHEMATICA_ANY; } => mathematica_ccallback;
73 *|;
74
75 # Entity machine
76
77 action mathematica_ecallback {
78 callback(MATHEMATICA_LANG, mathematica_entities[entity], cint(ts), cint(te),
79 userdata);
80 }
81
82 mathematica_comment_entity = '(*' >mathematica_comment_nc_res (
83 '(*' @mathematica_comment_nc_inc
84 |
85 '*)' @mathematica_comment_nc_dec
86 |
87 any
88 )* :>> ('*)' when { nest_count == 0 });
89
90 mathematica_entity := |*
91 space+ ${ entity = MATHEMATICA_SPACE; } => mathematica_ecallback;
92 mathematica_comment_entity ${ entity = MATHEMATICA_COMMENT; } => mathematica_ecallback;
93 # TODO:
94 ^space;
95 *|;
96 }%%
97
98 /************************* Required for every parser *************************/
99
100 /* Parses a string buffer with MATHEMATICA code.
101 *
102 * @param *buffer The string to parse.
103 * @param length The length of the string to parse.
104 * @param count Integer flag specifying whether or not to count lines. If yes,
105 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
106 * machine optimized for returning entity positions.
107 * @param *callback Callback function. If count is set, callback is called for
108 * every line of code, comment, or blank with 'lcode', 'lcomment', and
109 * 'lblank' respectively. Otherwise callback is called for each entity found.
110 */
111 void parse_mathematica(char *buffer, int length, int count,
112 void (*callback) (const char *lang, const char *entity, int s,
113 int e, void *udata),
114 void *userdata
115 ) {
116 init
117
118 int nest_count = 0;
119
120 %% write init;
121 cs = (count) ? mathematica_en_mathematica_line : mathematica_en_mathematica_entity;
122 %% write exec;
123
124 // if no newline at EOF; callback contents of last line
125 if (count) { process_last_line(MATHEMATICA_LANG) }
126 }
127
128 #endif
129
130 /*****************************************************************************/
0 // modula2.rl,
1 // derived from code written by Mitchell Foral. mitchell<att>caladbolg<dott>net
2
3
4 /************************* Required for every parser *************************/
5 #ifndef OHCOUNT_MODULA2_PARSER_H
6 #define OHCOUNT_MODULA2_PARSER_H
7
8 #include "../parser_macros.h"
9
10 // the name of the language
11 const char *MODULA2_LANG = LANG_MODULA2;
12
13 // the languages entities
14 const char *modula2_entities[] = {
15 "space", "comment", "string", "any"
16 };
17
18 // constants associated with the entities
19 enum {
20 MODULA2_SPACE = 0, MODULA2_COMMENT, MODULA2_STRING, MODULA2_ANY
21 };
22
23 /*****************************************************************************/
24
25 %%{
26 machine modula2;
27 write data;
28 include common "common.rl";
29
30 # Line counting machine
31
32 action modula2_ccallback {
33 switch(entity) {
34 case MODULA2_SPACE:
35 ls
36 break;
37 case MODULA2_ANY:
38 code
39 break;
40 case INTERNAL_NL:
41 std_internal_newline(MODULA2_LANG)
42 break;
43 case NEWLINE:
44 std_newline(MODULA2_LANG)
45 }
46 }
47
48
49 # Modula-2 comments
50
51 action modula2_comment_nc_res { nest_count = 0; }
52 action modula2_comment_nc_inc { nest_count++; }
53 action modula2_comment_nc_dec { nest_count--; }
54
55 modula2_comment =
56 '(*' >modula2_comment_nc_res @comment (
57 newline %{ entity = INTERNAL_NL; } %modula2_ccallback
58 |
59 ws
60 |
61 '(*' @modula2_comment_nc_inc @comment
62 |
63 '*)' @modula2_comment_nc_dec @comment
64 |
65 ^space @comment
66 )* :>> ('*)' when { nest_count == 0 }) @comment;
67
68
69 # Modula-2 string literals
70
71 modula2_singlequoted_string = '\'' @code [^\r\n\f"]* '\'';
72 modula2_doublequoted_string = '"' @code [^\r\n\f"]* '"';
73
74 modula2_string = modula2_singlequoted_string | modula2_doublequoted_string;
75
76
77 # Line counter
78
79 modula2_line := |*
80 spaces ${ entity = MODULA2_SPACE; } => modula2_ccallback;
81 modula2_comment;
82 modula2_string;
83 newline ${ entity = NEWLINE; } => modula2_ccallback;
84 ^space ${ entity = MODULA2_ANY; } => modula2_ccallback;
85 *|;
86
87
88 # Entity machine
89
90 action modula2_ecallback {
91 callback(MODULA2_LANG, modula2_entities[entity], cint(ts), cint(te),
92 userdata);
93 }
94
95 modula2_comment_entity = '(*' >modula2_comment_nc_res (
96 '(*' @modula2_comment_nc_inc
97 |
98 '*)' @modula2_comment_nc_dec
99 |
100 any
101 )* :>> ('*)' when { nest_count == 0 });
102
103 modula2_string_entity = sq_str | dq_str;
104
105 modula2_entity := |*
106 space+ ${ entity = MODULA2_SPACE; } => modula2_ecallback;
107 modula2_comment_entity ${ entity = MODULA2_COMMENT; } => modula2_ecallback;
108 modula2_string_entity ${ entity = MODULA2_STRING; } => modula2_ecallback;
109 # TODO: detecting other entities may be useful to differentiate dialects
110 ^space;
111 *|;
112 }%%
113
114 /************************* Required for every parser *************************/
115
116 /* Parses a string buffer with Modula-2 code.
117 *
118 * @param *buffer The string to parse.
119 * @param length The length of the string to parse.
120 * @param count Integer flag specifying whether or not to count lines. If yes,
121 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
122 * machine optimized for returning entity positions.
123 * @param *callback Callback function. If count is set, callback is called for
124 * every line of code, comment, or blank with 'lcode', 'lcomment', and
125 * 'lblank' respectively. Otherwise callback is called for each entity found.
126 */
127 void parse_modula2(char *buffer, int length, int count,
128 void (*callback) (const char *lang, const char *entity, int s,
129 int e, void *udata),
130 void *userdata
131 ) {
132 init
133
134 int nest_count = 0;
135
136 %% write init;
137 cs = (count) ? modula2_en_modula2_line : modula2_en_modula2_entity;
138 %% write exec;
139
140 // if no newline at EOF; callback contents of last line
141 if (count) { process_last_line(MODULA2_LANG) }
142 }
143
144 #endif
145
146 /*****************************************************************************/
0 // modula3.rl,
1 // derived from code written by Mitchell Foral. mitchell<att>caladbolg<dott>net
2
3
4 /************************* Required for every parser *************************/
5 #ifndef OHCOUNT_MODULA3_PARSER_H
6 #define OHCOUNT_MODULA3_PARSER_H
7
8 #include "../parser_macros.h"
9
10 // the name of the language
11 const char *MODULA3_LANG = LANG_MODULA3;
12
13 // the languages entities
14 const char *modula3_entities[] = {
15 "space", "comment", "string", "any"
16 };
17
18 // constants associated with the entities
19 enum {
20 MODULA3_SPACE = 0, MODULA3_COMMENT, MODULA3_STRING, MODULA3_ANY
21 };
22
23 /*****************************************************************************/
24
25 %%{
26 machine modula3;
27 write data;
28 include common "common.rl";
29
30 # Line counting machine
31
32 action modula3_ccallback {
33 switch(entity) {
34 case MODULA3_SPACE:
35 ls
36 break;
37 case MODULA3_ANY:
38 code
39 break;
40 case INTERNAL_NL:
41 std_internal_newline(MODULA3_LANG)
42 break;
43 case NEWLINE:
44 std_newline(MODULA3_LANG)
45 }
46 }
47
48
49 # Modula-3 comments
50
51 action modula3_comment_nc_res { nest_count = 0; }
52 action modula3_comment_nc_inc { nest_count++; }
53 action modula3_comment_nc_dec { nest_count--; }
54
55 modula3_comment =
56 '(*' >modula3_comment_nc_res @comment (
57 newline %{ entity = INTERNAL_NL; } %modula3_ccallback
58 |
59 ws
60 |
61 '(*' @modula3_comment_nc_inc @comment
62 |
63 '*)' @modula3_comment_nc_dec @comment
64 |
65 ^space @comment
66 )* :>> ('*)' when { nest_count == 0 }) @comment;
67
68
69 # Modula-3 string literals
70
71 modula3_singlequoted_string =
72 '\'' @code (
73 escaped_newline %{ entity = INTERNAL_NL; } %modula3_ccallback
74 |
75 ws
76 |
77 [^\t '\\] @code
78 |
79 '\\' nonnewline @code
80 )* '\'';
81 modula3_doublequoted_string =
82 '"' @code (
83 escaped_newline %{ entity = INTERNAL_NL; } %modula3_ccallback
84 |
85 ws
86 |
87 [^\t "\\] @code
88 |
89 '\\' nonnewline @code
90 )* '"';
91 modula3_string = modula3_singlequoted_string | modula3_doublequoted_string;
92
93
94 # Line counter
95
96 modula3_line := |*
97 spaces ${ entity = MODULA3_SPACE; } => modula3_ccallback;
98 modula3_comment;
99 modula3_string;
100 newline ${ entity = NEWLINE; } => modula3_ccallback;
101 ^space ${ entity = MODULA3_ANY; } => modula3_ccallback;
102 *|;
103
104
105 # Entity machine
106
107 action modula3_ecallback {
108 callback(MODULA3_LANG, modula3_entities[entity], cint(ts), cint(te),
109 userdata);
110 }
111
112 modula3_comment_entity = '(*' >modula3_comment_nc_res (
113 '(*' @modula3_comment_nc_inc
114 |
115 '*)' @modula3_comment_nc_dec
116 |
117 any
118 )* :>> ('*)' when { nest_count == 0 });
119
120 modula3_string_entity = sq_str_with_escapes |
121 dq_str_with_escapes;
122
123 modula3_entity := |*
124 space+ ${ entity = MODULA3_SPACE; } => modula3_ecallback;
125 modula3_comment_entity ${ entity = MODULA3_COMMENT; } => modula3_ecallback;
126 modula3_string_entity ${ entity = MODULA3_STRING; } => modula3_ecallback;
127 # TODO: detecting other entities may be useful to differentiate dialects
128 ^space;
129 *|;
130 }%%
131
132 /************************* Required for every parser *************************/
133
134 /* Parses a string buffer with Modula-3 code.
135 *
136 * @param *buffer The string to parse.
137 * @param length The length of the string to parse.
138 * @param count Integer flag specifying whether or not to count lines. If yes,
139 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
140 * machine optimized for returning entity positions.
141 * @param *callback Callback function. If count is set, callback is called for
142 * every line of code, comment, or blank with 'lcode', 'lcomment', and
143 * 'lblank' respectively. Otherwise callback is called for each entity found.
144 */
145 void parse_modula3(char *buffer, int length, int count,
146 void (*callback) (const char *lang, const char *entity, int s,
147 int e, void *udata),
148 void *userdata
149 ) {
150 init
151
152 int nest_count = 0;
153
154 %% write init;
155 cs = (count) ? modula3_en_modula3_line : modula3_en_modula3_entity;
156 %% write exec;
157
158 // if no newline at EOF; callback contents of last line
159 if (count) { process_last_line(MODULA3_LANG) }
160 }
161
162 #endif
163
164 /*****************************************************************************/
0 // nsis.rl written by Chris Morgan.
1
2 /************************* Required for every parser *************************/
3 #ifndef OHCOUNT_NSIS_PARSER_H
4 #define OHCOUNT_NSIS_PARSER_H
5
6 #include "../parser_macros.h"
7
8 // the name of the language
9 const char *NSIS_LANG = LANG_NSIS;
10
11 // the languages entities
12 const char *nsis_entities[] = {
13 "space", "comment", "string", "any"
14 };
15
16 // constants associated with the entities
17 enum {
18 NSIS_SPACE = 0, NSIS_COMMENT, NSIS_STRING, NSIS_ANY
19 };
20
21 /*****************************************************************************/
22
23 %%{
24 machine nsis;
25 write data;
26 include common "common.rl";
27
28 # Line counting machine
29
30 action nsis_ccallback {
31 switch(entity) {
32 case NSIS_SPACE:
33 ls
34 break;
35 case NSIS_ANY:
36 code
37 break;
38 case INTERNAL_NL:
39 std_internal_newline(NSIS_LANG)
40 break;
41 case NEWLINE:
42 std_newline(NSIS_LANG)
43 }
44 }
45
46 nsis_line_comment = ('#' | ';') @comment nonnewline*;
47 nsis_block_comment =
48 '/*' @comment (
49 newline %{ entity = INTERNAL_NL; } %nsis_ccallback
50 |
51 ws
52 |
53 (nonnewline - ws) @comment
54 )* :>> '*/';
55 nsis_comment = nsis_line_comment | nsis_block_comment;
56
57 nsis_bt_str = '`' @code ([^\r\n\f`\\] | '\\' nonnewline)* '`';
58 nsis_sq_str = '\'' @code ([^\r\n\f'\\] | '\\' nonnewline)* '\'';
59 nsis_dq_str = '"' @code ([^\r\n\f"\\] | '\\' nonnewline)* '"';
60 nsis_string = nsis_bt_str | nsis_sq_str | nsis_dq_str;
61
62 nsis_line := |*
63 spaces ${ entity = NSIS_SPACE; } => nsis_ccallback;
64 nsis_comment;
65 nsis_string;
66 newline ${ entity = NEWLINE; } => nsis_ccallback;
67 ^space ${ entity = NSIS_ANY; } => nsis_ccallback;
68 *|;
69
70 # Entity machine
71
72 action nsis_ecallback {
73 callback(NSIS_LANG, nsis_entities[entity], cint(ts), cint(te), userdata);
74 }
75
76 nsis_line_comment_entity = ('#' | '//') nonnewline*;
77 nsis_block_comment_entity = '/*' any* :>> '*/';
78 nsis_comment_entity = nsis_line_comment_entity | nsis_block_comment_entity;
79
80 nsis_entity := |*
81 space+ ${ entity = NSIS_SPACE; } => nsis_ecallback;
82 nsis_comment_entity ${ entity = NSIS_COMMENT; } => nsis_ecallback;
83 # TODO:
84 ^space;
85 *|;
86 }%%
87
88 /************************* Required for every parser *************************/
89
90 /* Parses a string buffer with NSIS code.
91 *
92 * @param *buffer The string to parse.
93 * @param length The length of the string to parse.
94 * @param count Integer flag specifying whether or not to count lines. If yes,
95 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
96 * machine optimized for returning entity positions.
97 * @param *callback Callback function. If count is set, callback is called for
98 * every line of code, comment, or blank with 'lcode', 'lcomment', and
99 * 'lblank' respectively. Otherwise callback is called for each entity found.
100 */
101 void parse_nsis(char *buffer, int length, int count,
102 void (*callback) (const char *lang, const char *entity, int s,
103 int e, void *udata),
104 void *userdata
105 ) {
106 init
107
108 %% write init;
109 cs = (count) ? nsis_en_nsis_line : nsis_en_nsis_entity;
110 %% write exec;
111
112 // if no newline at EOF; callback contents of last line
113 if (count) { process_last_line(NSIS_LANG) }
114 }
115
116 #endif
117
118 /*****************************************************************************/
0 // oberon.rl,
1 // derived from code written by Mitchell Foral. mitchell<att>caladbolg<dott>net
2
3
4 /************************* Required for every parser *************************/
5 #ifndef OHCOUNT_OBERON_PARSER_H
6 #define OHCOUNT_OBERON_PARSER_H
7
8 #include "../parser_macros.h"
9
10 // the name of the language
11 const char *OBERON_LANG = LANG_OBERON;
12
13 // the languages entities
14 const char *oberon_entities[] = {
15 "space", "comment", "string", "any"
16 };
17
18 // constants associated with the entities
19 enum {
20 OBERON_SPACE = 0, OBERON_COMMENT, OBERON_STRING, OBERON_ANY
21 };
22
23 /*****************************************************************************/
24
25 %%{
26 machine oberon;
27 write data;
28 include common "common.rl";
29
30 # Line counting machine
31
32 action oberon_ccallback {
33 switch(entity) {
34 case OBERON_SPACE:
35 ls
36 break;
37 case OBERON_ANY:
38 code
39 break;
40 case INTERNAL_NL:
41 std_internal_newline(OBERON_LANG)
42 break;
43 case NEWLINE:
44 std_newline(OBERON_LANG)
45 }
46 }
47
48
49 # Oberon comments
50
51 action oberon_comment_nc_res { nest_count = 0; }
52 action oberon_comment_nc_inc { nest_count++; }
53 action oberon_comment_nc_dec { nest_count--; }
54
55 oberon_comment =
56 '(*' >oberon_comment_nc_res @comment (
57 newline %{ entity = INTERNAL_NL; } %oberon_ccallback
58 |
59 ws
60 |
61 '(*' @oberon_comment_nc_inc @comment
62 |
63 '*)' @oberon_comment_nc_dec @comment
64 |
65 ^space @comment
66 )* :>> ('*)' when { nest_count == 0 }) @comment;
67
68
69 # Oberon string literals
70
71 oberon_singlequoted_string = '\'' @code [^\r\n\f"]* '\'';
72 oberon_doublequoted_string = '"' @code [^\r\n\f"]* '"';
73
74 oberon_string = oberon_singlequoted_string | oberon_doublequoted_string;
75
76
77 # Line counter
78
79 oberon_line := |*
80 spaces ${ entity = OBERON_SPACE; } => oberon_ccallback;
81 oberon_comment;
82 oberon_string;
83 newline ${ entity = NEWLINE; } => oberon_ccallback;
84 ^space ${ entity = OBERON_ANY; } => oberon_ccallback;
85 *|;
86
87
88 # Entity machine
89
90 action oberon_ecallback {
91 callback(OBERON_LANG, oberon_entities[entity], cint(ts), cint(te),
92 userdata);
93 }
94
95 oberon_comment_entity = '(*' >oberon_comment_nc_res (
96 '(*' @oberon_comment_nc_inc
97 |
98 '*)' @oberon_comment_nc_dec
99 |
100 any
101 )* :>> ('*)' when { nest_count == 0 });
102
103 oberon_string_entity = sq_str | dq_str;
104
105 oberon_entity := |*
106 space+ ${ entity = OBERON_SPACE; } => oberon_ecallback;
107 oberon_comment_entity ${ entity = OBERON_COMMENT; } => oberon_ecallback;
108 oberon_string_entity ${ entity = OBERON_STRING; } => oberon_ecallback;
109 # TODO: detecting other entities may be useful to differentiate dialects
110 ^space;
111 *|;
112 }%%
113
114 /************************* Required for every parser *************************/
115
116 /* Parses a string buffer with Oberon code.
117 *
118 * @param *buffer The string to parse.
119 * @param length The length of the string to parse.
120 * @param count Integer flag specifying whether or not to count lines. If yes,
121 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
122 * machine optimized for returning entity positions.
123 * @param *callback Callback function. If count is set, callback is called for
124 * every line of code, comment, or blank with 'lcode', 'lcomment', and
125 * 'lblank' respectively. Otherwise callback is called for each entity found.
126 */
127 void parse_oberon(char *buffer, int length, int count,
128 void (*callback) (const char *lang, const char *entity, int s,
129 int e, void *udata),
130 void *userdata
131 ) {
132 init
133
134 int nest_count = 0;
135
136 %% write init;
137 cs = (count) ? oberon_en_oberon_line : oberon_en_oberon_entity;
138 %% write exec;
139
140 // if no newline at EOF; callback contents of last line
141 if (count) { process_last_line(OBERON_LANG) }
142 }
143
144 #endif
145
146 /*****************************************************************************/
0 // prolog.rl written by Paulo Moura. pmoura<att>prolog<dott>org.
1
2 /************************* Required for every parser *************************/
3 #ifndef OHCOUNT_PROLOG_PARSER_H
4 #define OHCOUNT_PROLOG_PARSER_H
5
6 #include "../parser_macros.h"
7
8 // the name of the language
9 const char *PROLOG_LANG = LANG_PROLOG;
10
11 // the languages entities
12 const char *prolog_entities[] = {
13 "space", "comment", "string", "any"
14 };
15
16 // constants associated with the entities
17 enum {
18 PROLOG_SPACE = 0, PROLOG_COMMENT, PROLOG_STRING, PROLOG_ANY
19 };
20
21 /*****************************************************************************/
22
23 %%{
24 machine prolog;
25 write data;
26 include common "common.rl";
27
28 # Line counting machine
29
30 action prolog_ccallback {
31 switch(entity) {
32 case PROLOG_SPACE:
33 ls
34 break;
35 case PROLOG_ANY:
36 code
37 break;
38 case INTERNAL_NL:
39 std_internal_newline(PROLOG_LANG)
40 break;
41 case NEWLINE:
42 std_newline(PROLOG_LANG)
43 }
44 }
45
46 prolog_line_comment = '%' @comment nonnewline*;
47 prolog_block_comment =
48 '/*' @comment (
49 newline %{ entity = INTERNAL_NL; } %prolog_ccallback
50 |
51 ws
52 |
53 (nonnewline - ws) @comment
54 )* :>> '*/';
55 prolog_comment = prolog_line_comment | prolog_block_comment;
56
57 prolog_sq_str = '\'' @code ([^\r\n\f'\\] | '\\' nonnewline)* '\'';
58 prolog_dq_str = '"' @code ([^\r\n\f"\\] | '\\' nonnewline)* '"';
59 prolog_string = prolog_sq_str | prolog_dq_str;
60
61 prolog_line := |*
62 spaces ${ entity = PROLOG_SPACE; } => prolog_ccallback;
63 prolog_comment;
64 prolog_string;
65 newline ${ entity = NEWLINE; } => prolog_ccallback;
66 ^space ${ entity = PROLOG_ANY; } => prolog_ccallback;
67 *|;
68
69 # Entity machine
70
71 action prolog_ecallback {
72 callback(PROLOG_LANG, prolog_entities[entity], cint(ts), cint(te),
73 userdata);
74 }
75
76 prolog_line_comment_entity = '%' nonnewline*;
77 prolog_block_comment_entity = '/*' any* :>> '*/';
78 prolog_comment_entity = prolog_line_comment_entity | prolog_block_comment_entity;
79
80 prolog_entity := |*
81 space+ ${ entity = PROLOG_SPACE; } => prolog_ecallback;
82 prolog_comment_entity ${ entity = PROLOG_COMMENT; } => prolog_ecallback;
83 # TODO:
84 ^space;
85 *|;
86 }%%
87
88 /************************* Required for every parser *************************/
89
90 /* Parses a string buffer with Prolog code.
91 *
92 * @param *buffer The string to parse.
93 * @param length The length of the string to parse.
94 * @param count Integer flag specifying whether or not to count lines. If yes,
95 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
96 * machine optimized for returning entity positions.
97 * @param *callback Callback function. If count is set, callback is called for
98 * every line of code, comment, or blank with 'lcode', 'lcomment', and
99 * 'lblank' respectively. Otherwise callback is called for each entity found.
100 */
101 void parse_prolog(char *buffer, int length, int count,
102 void (*callback) (const char *lang, const char *entity, int s,
103 int e, void *udata),
104 void *userdata
105 ) {
106 init
107
108 %% write init;
109 cs = (count) ? prolog_en_prolog_line : prolog_en_prolog_entity;
110 %% write exec;
111
112 // if no newline at EOF; callback contents of last line
113 if (count) { process_last_line(PROLOG_LANG) }
114 }
115
116 #endif
117
118 /*****************************************************************************/
0 // puppet.rl written by Ken Barber <ken@bob.sh>
1 // Based on pascal.rl by Mitchell Foral. mitchell<att>caladbolg<dott>net
2
3 /************************* Required for every parser *************************/
4 #ifndef OHCOUNT_PUPPET_PARSER_H
5 #define OHCOUNT_PUPPET_PARSER_H
6
7 #include "../parser_macros.h"
8
9 // the name of the language
10 const char *PUPPET_LANG = LANG_PUPPET;
11
12 // the languages entities
13 const char *puppet_entities[] = {
14 "space", "comment", "string", "any"
15 };
16
17 // constants associated with the entities
18 enum {
19 PUPPET_SPACE = 0, PUPPET_COMMENT, PUPPET_STRING, PUPPET_ANY
20 };
21
22 /*****************************************************************************/
23
24 %%{
25 machine puppet;
26 write data;
27 include common "common.rl";
28
29 # Line counting machine
30
31 action puppet_ccallback {
32 switch(entity) {
33 case PUPPET_SPACE:
34 ls
35 break;
36 case PUPPET_ANY:
37 code
38 break;
39 case INTERNAL_NL:
40 std_internal_newline(PUPPET_LANG)
41 break;
42 case NEWLINE:
43 std_newline(PUPPET_LANG)
44 }
45 }
46
47 puppet_line_comment = '#' @comment nonnewline*;
48 puppet_block_comment =
49 '/*' @comment (
50 newline %{ entity = INTERNAL_NL; } %puppet_ccallback
51 |
52 ws
53 |
54 (nonnewline - ws) @code
55 )* :>> '*/';
56 puppet_comment = puppet_line_comment | puppet_block_comment;
57
58 puppet_string =
59 '\'' @code (
60 newline %{ entity = INTERNAL_NL; } %puppet_ccallback
61 |
62 ws
63 |
64 [^\r\n\f\t '\\] @code
65 |
66 '\\' nonnewline @code
67 )* '\'';
68
69 puppet_line := |*
70 spaces ${ entity = PUPPET_SPACE; } => puppet_ccallback;
71 puppet_comment;
72 puppet_string;
73 newline ${ entity = NEWLINE; } => puppet_ccallback;
74 ^space ${ entity = PUPPET_ANY; } => puppet_ccallback;
75 *|;
76
77 # Entity machine
78
79 action puppet_ecallback {
80 callback(PUPPET_LANG, puppet_entities[entity], cint(ts), cint(te),
81 userdata);
82 }
83
84 puppet_line_comment_entity = '#' nonnewline*;
85 puppet_block_comment_entity = '/*' any* :>> '*/';
86 puppet_comment_entity = puppet_line_comment_entity |
87 puppet_block_comment_entity;
88
89 puppet_entity := |*
90 space+ ${ entity = PUPPET_SPACE; } => puppet_ecallback;
91 puppet_comment_entity ${ entity = PUPPET_COMMENT; } => puppet_ecallback;
92 # TODO:
93 ^space;
94 *|;
95 }%%
96
97 /************************* Required for every parser *************************/
98
99 /* Parses a string buffer with Puppet DSL code.
100 *
101 * @param *buffer The string to parse.
102 * @param length The length of the string to parse.
103 * @param count Integer flag specifying whether or not to count lines. If yes,
104 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
105 * machine optimized for returning entity positions.
106 * @param *callback Callback function. If count is set, callback is called for
107 * every line of code, comment, or blank with 'lcode', 'lcomment', and
108 * 'lblank' respectively. Otherwise callback is called for each entity found.
109 */
110 void parse_puppet(char *buffer, int length, int count,
111 void (*callback) (const char *lang, const char *entity, int s,
112 int e, void *udata),
113 void *userdata
114 ) {
115 init
116
117 %% write init;
118 cs = (count) ? puppet_en_puppet_line : puppet_en_puppet_entity;
119 %% write exec;
120
121 // if no newline at EOF; callback contents of last line
122 if (count) { process_last_line(PUPPET_LANG) }
123 }
124
125 #endif
126
127 /*****************************************************************************/
0 // rebol.rl written by Andreas Bolka.
1
2 /************************* Required for every parser *************************/
3 #ifndef OHCOUNT_REBOL_PARSER_H
4 #define OHCOUNT_REBOL_PARSER_H
5
6 #include "../parser_macros.h"
7
8 // the name of the language
9 const char *REBOL_LANG = LANG_REBOL;
10
11 // the languages entities
12 const char *rebol_entities[] = {
13 "space", "comment", "string", "any"
14 };
15
16 // constants associated with the entities
17 enum {
18 REBOL_SPACE = 0, REBOL_COMMENT, REBOL_STRING, REBOL_ANY
19 };
20
21 /*****************************************************************************/
22
23 %%{
24 machine rebol;
25 write data;
26 include common "common.rl";
27
28 action rebol_inc_string { ++rebol_string_level; }
29 action rebol_dec_string { --rebol_string_level; }
30 action rebol_is_nested { rebol_string_level > 0 }
31
32 rebol_cb_str_nest = '{' %rebol_inc_string
33 | '}' when rebol_is_nested %rebol_dec_string;
34
35 # Line counting machine
36
37 action rebol_ccallback {
38 switch(entity) {
39 case REBOL_SPACE:
40 ls
41 break;
42 case REBOL_ANY:
43 code
44 break;
45 case INTERNAL_NL:
46 std_internal_newline(REBOL_LANG)
47 break;
48 case NEWLINE:
49 std_newline(REBOL_LANG)
50 }
51 }
52
53 rebol_line_comment = ';' @comment nonnewline*;
54 rebol_comment = rebol_line_comment;
55
56 rebol_dq_str = '"' @code ([^\r\n\f"] | '^"')* [\r\n\f"];
57 rebol_cb_str_inner = [^{}] | '^{' | '^}'
58 | newline %{ entity = INTERNAL_NL; } %rebol_ccallback
59 | rebol_cb_str_nest;
60 rebol_cb_str = '{' @code rebol_cb_str_inner* @code '}' @code;
61 rebol_string = rebol_dq_str | rebol_cb_str;
62
63 rebol_line := |*
64 spaces ${ entity = REBOL_SPACE; } => rebol_ccallback;
65 rebol_comment;
66 rebol_string;
67 newline ${ entity = NEWLINE; } => rebol_ccallback;
68 ^space ${ entity = REBOL_ANY; } => rebol_ccallback;
69 *|;
70
71 # Entity machine
72
73 action rebol_ecallback {
74 callback(REBOL_LANG, rebol_entities[entity], cint(ts), cint(te), userdata);
75 }
76
77 rebol_line_comment_entity = ';' nonnewline*;
78 rebol_comment_entity = rebol_line_comment_entity;
79
80 rebol_dq_str_entity = '"' ([^\r\n\f"] | '^"')* [\r\n\f"];
81 rebol_cb_str_entity = '{' ([^{}] | '^{' | '^}' | rebol_cb_str_nest)* '}';
82 rebol_string_entiy = rebol_dq_str_entity | rebol_cb_str_entity;
83
84 rebol_entity := |*
85 space+ ${ entity = REBOL_SPACE; } => rebol_ecallback;
86 rebol_comment_entity ${ entity = REBOL_COMMENT; } => rebol_ecallback;
87 rebol_string_entiy ${ entity = REBOL_STRING; } => rebol_ecallback;
88 ^space ${ entity = REBOL_ANY; } => rebol_ecallback;
89 *|;
90
91 }%%
92
93 /************************* Required for every parser *************************/
94
95 /* Parses a string buffer with REBOL code.
96 *
97 * @param *buffer The string to parse.
98 * @param length The length of the string to parse.
99 * @param count Integer flag specifying whether or not to count lines. If yes,
100 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
101 * machine optimized for returning entity positions.
102 * @param *callback Callback function. If count is set, callback is called for
103 * every line of code, comment, or blank with 'lcode', 'lcomment', and
104 * 'lblank' respectively. Otherwise callback is called for each entity found.
105 */
106 void parse_rebol(char *buffer, int length, int count,
107 void (*callback) (const char *lang, const char *entity, int s,
108 int e, void *udata),
109 void *userdata
110 ) {
111 // For {..} multi-line strings which require proper balancing of {}'s.
112 int rebol_string_level = 0;
113 init
114
115 %% write init;
116 cs = (count) ? rebol_en_rebol_line : rebol_en_rebol_entity;
117 %% write exec;
118
119 // if no newline at EOF; callback contents of last line
120 if (count) { process_last_line(REBOL_LANG) }
121 }
122
123 #endif
124
125 /*****************************************************************************/
126
127 // vim: set ts=2 syn=c:
0 // rust.rl written by Sébastien Crozet <developer@crozet.re>
1 // Inpired by golang.rl
2
3 /************************* Required for every parser *************************/
4 #ifndef OHCOUNT_RUST_PARSER_H
5 #define OHCOUNT_RUST_PARSER_H
6
7 #include "../parser_macros.h"
8
9 // the name of the language
10 const char *RUST_LANG = LANG_RUST;
11
12 // the languages entities
13 const char *rust_entities[] = {
14 "space", "comment", "string", "number",
15 "keyword", "identifier", "operator", "any"
16 };
17
18 // constants associated with the entities
19 enum {
20 RUST_SPACE = 0, RUST_COMMENT, RUST_STRING, RUST_NUMBER,
21 RUST_KEYWORD, RUST_IDENTIFIER, RUST_OPERATOR, RUST_ANY
22 };
23
24 /*****************************************************************************/
25
26 %%{
27 machine rust;
28 write data;
29 include common "common.rl";
30
31 # Line counting machine
32
33 action rust_ccallback {
34 switch(entity) {
35 case RUST_SPACE:
36 ls
37 break;
38 case RUST_ANY:
39 code
40 break;
41 case INTERNAL_NL:
42 std_internal_newline(RUST_LANG)
43 break;
44 case NEWLINE:
45 std_newline(RUST_LANG)
46 }
47 }
48
49 rust_line_comment =
50 '//' @comment (
51 escaped_newline %{ entity = INTERNAL_NL; } %rust_ccallback
52 |
53 ws
54 |
55 (nonnewline - ws) @comment
56 )*;
57 rust_block_comment =
58 '/*' @comment (
59 newline %{ entity = INTERNAL_NL; } %rust_ccallback
60 |
61 ws
62 |
63 (nonnewline - ws) @comment
64 )* :>> '*/';
65 rust_comment = rust_line_comment | rust_block_comment;
66
67 rust_dq_str =
68 '"' @code (
69 escaped_newline %{ entity = INTERNAL_NL; } %rust_ccallback
70 |
71 ws
72 |
73 [^\t "\\] @code
74 |
75 '\\' nonnewline @code
76 )* '"';
77 rust_string = rust_dq_str;
78
79 rust_line := |*
80 spaces ${ entity = RUST_SPACE; } => rust_ccallback;
81 rust_comment;
82 rust_string;
83 newline ${ entity = NEWLINE; } => rust_ccallback;
84 ^space ${ entity = RUST_ANY; } => rust_ccallback;
85 *|;
86
87 # Entity machine
88
89 action rust_ecallback {
90 callback(RUST_LANG, rust_entities[entity], cint(ts), cint(te), userdata);
91 }
92
93 rust_line_comment_entity = '//' (escaped_newline | nonnewline)*;
94 rust_block_comment_entity = '/*' any* :>> '*/';
95 rust_comment_entity = rust_line_comment_entity | rust_block_comment_entity;
96
97 rust_string_entity = dq_str_with_escapes;
98
99 # Up to and including "the number entity" these are almost verbatim from the
100 # "number literals" section of the Rust reference manual
101 rust_int_suffix = [iu] ('8' | '16' | '32' | '64')?;
102
103 rust_float_suffix_ty = 'f' ('32' | '64');
104 rust_dec_lit = [0-9_]+;
105 rust_exponent = [Ee] [\-+]? rust_dec_lit;
106 rust_float_suffix = (rust_exponent | '.' rust_dec_lit rust_exponent?)?
107 rust_float_suffix_ty?;
108
109 rust_num_suffix = rust_int_suffix | rust_float_suffix;
110
111 rust_number_entity = [1-9] [0-9_]* rust_num_suffix?
112 | '0' ( [0-9_]* rust_num_suffix?
113 | 'b' [01_]+ rust_int_suffix?
114 | 'o' [0-7_]+ rust_int_suffix?
115 | 'x' [0-9A-Fa-f_]+ rust_int_suffix?);
116
117 rust_identifier_entity = (alpha | '_') (alnum | '_')*;
118
119 rust_keyword_entity =
120 'alignof' | 'as' | 'be' | 'break' | 'const' | 'continue' | 'do' | 'else' |
121 'enum' | 'extern' | 'false' | 'fn' | 'for' | 'if' | 'impl' | 'impl' |
122 'in' | 'let' | 'let' | 'log' | 'log' | 'loop' | 'match' | 'mod' | 'mod' |
123 'mut' | 'offsetof' | 'once' | 'priv' | 'pub' | 'pure' | 'ref' | 'return' |
124 'self' | 'sizeof' | 'static' | 'struct' | 'super' | 'trait' | 'true' |
125 'type' | 'typeof' | 'unsafe' | 'use' | 'while' | 'yield';
126
127 rust_operator_entity = [+\-/*%<>!=^&|?~:;.,()\[\]{}@];
128
129 rust_entity := |*
130 space+ ${ entity = RUST_SPACE; } => rust_ecallback;
131 rust_comment_entity ${ entity = RUST_COMMENT; } => rust_ecallback;
132 rust_string_entity ${ entity = RUST_STRING; } => rust_ecallback;
133 rust_number_entity ${ entity = RUST_NUMBER; } => rust_ecallback;
134 rust_identifier_entity ${ entity = RUST_IDENTIFIER; } => rust_ecallback;
135 rust_keyword_entity ${ entity = RUST_KEYWORD; } => rust_ecallback;
136 rust_operator_entity ${ entity = RUST_OPERATOR; } => rust_ecallback;
137 ^(space | digit) ${ entity = RUST_ANY; } => rust_ecallback;
138 *|;
139 }%%
140
141 /************************* Required for every parser *************************/
142
143 /* Parses a string buffer with C/C++ code.
144 *
145 * @param *buffer The string to parse.
146 * @param length The length of the string to parse.
147 * @param count Integer flag specifying whether or not to count lines. If yes,
148 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
149 * machine optimized for returning entity positions.
150 * @param *callback Callback function. If count is set, callback is called for
151 * every line of code, comment, or blank with 'lcode', 'lcomment', and
152 * 'lblank' respectively. Otherwise callback is called for each entity found.
153 */
154 void parse_rust(char *buffer, int length, int count,
155 void (*callback) (const char *lang, const char *entity, int s,
156 int e, void *udata),
157 void *userdata
158 ) {
159 init
160
161 %% write init;
162 cs = (count) ? rust_en_rust_line : rust_en_rust_entity;
163 %% write exec;
164
165 // if no newline at EOF; callback contents of last line
166 if (count) { process_last_line(RUST_LANG) }
167 }
168
169 const char *ORIG_RUST_LANG = LANG_RUST;
170
171 #endif
172
173 /*****************************************************************************/
4949 '\'' @enqueue @code (
5050 newline %{ entity = INTERNAL_NL; } %shell_ccallback
5151 |
52 '\\' newline %{ entity = INTERNAL_NL; } %shell_ccallback
53 |
5254 ws
5355 |
5456 [^\r\n\f\t '\\] @code
5860 shell_dq_str =
5961 '"' @enqueue @code (
6062 newline %{ entity = INTERNAL_NL; } %shell_ccallback
63 |
64 '\\' newline %{ entity = INTERNAL_NL; } %shell_ccallback
6165 |
6266 ws
6367 |
0 // tex_dtx.rl written by Raphael Pinson,
1 // based on tex.rl by Mitchell Foral. mitchell<att>caladbolg<dott>net.
2
3 /************************* Required for every parser *************************/
4 #ifndef OHCOUNT_TEX_DTX_PARSER_H
5 #define OHCOUNT_TEX_DTX_PARSER_H
6
7 #include "../parser_macros.h"
8
9 // the name of the language
10 const char *TEX_DTX_LANG = LANG_TEX_DTX;
11
12 // the languages entities
13 const char *tex_dtx_entities[] = {
14 "space", "comment", "string", "any"
15 };
16
17 // constants associated with the entities
18 enum {
19 TEX_DTX_SPACE = 0, TEX_DTX_COMMENT, TEX_DTX_STRING, TEX_DTX_ANY
20 };
21
22 /*****************************************************************************/
23
24 %%{
25 machine tex_dtx;
26 write data;
27 include common "common.rl";
28
29 # Line counting machine
30
31 action tex_dtx_ccallback {
32 switch(entity) {
33 case TEX_DTX_SPACE:
34 ls
35 break;
36 case TEX_DTX_ANY:
37 code
38 break;
39 case INTERNAL_NL:
40 std_internal_newline(TEX_DTX_LANG)
41 break;
42 case NEWLINE:
43 std_newline(TEX_DTX_LANG)
44 }
45 }
46
47 tex_dtx_comment = '%%' @comment nonnewline*;
48
49 tex_dtx_line := |*
50 spaces ${ entity = TEX_DTX_SPACE; } => tex_dtx_ccallback;
51 tex_dtx_comment;
52 newline ${ entity = NEWLINE; } => tex_dtx_ccallback;
53 ^space ${ entity = TEX_DTX_ANY; } => tex_dtx_ccallback;
54 *|;
55
56 # Entity machine
57
58 action tex_dtx_ecallback {
59 callback(TEX_DTX_LANG, tex_dtx_entities[entity], cint(ts), cint(te), userdata);
60 }
61
62 tex_dtx_comment_entity = '%%' nonnewline*;
63
64 tex_dtx_entity := |*
65 space+ ${ entity = TEX_DTX_SPACE; } => tex_dtx_ecallback;
66 tex_dtx_comment_entity ${ entity = TEX_DTX_COMMENT; } => tex_dtx_ecallback;
67 # TODO:
68 ^space;
69 *|;
70 }%%
71
72 /************************* Required for every parser *************************/
73
74 /* Parses a string buffer with Tex markup.
75 *
76 * @param *buffer The string to parse.
77 * @param length The length of the string to parse.
78 * @param count Integer flag specifying whether or not to count lines. If yes,
79 * uses the Ragel machine optimized for counting. Otherwise uses the Ragel
80 * machine optimized for returning entity positions.
81 * @param *callback Callback function. If count is set, callback is called for
82 * every line of code, comment, or blank with 'lcode', 'lcomment', and
83 * 'lblank' respectively. Otherwise callback is called for each entity found.
84 */
85 void parse_tex_dtx(char *buffer, int length, int count,
86 void (*callback) (const char *lang, const char *entity, int s,
87 int e, void *udata),
88 void *userdata
89 ) {
90 init
91
92 %% write init;
93 cs = (count) ? tex_dtx_en_tex_dtx_line : tex_dtx_en_tex_dtx_entity;
94 %% write exec;
95
96 // if no newline at EOF; callback contents of last line
97 if (count) { process_last_line(TEX_DTX_LANG) }
98 }
99
100 #endif
101
102 /*****************************************************************************/
44 #include <stdio.h>
55 #include <stdlib.h>
66 #include <string.h>
7
8 #include <sys/types.h>
9 #include <sys/stat.h>
10 #include <unistd.h>
711
812 #include "detector.h"
913 #include "diff.h"
7983 char *path = sourcefile->filepath;
8084 if (sourcefile->diskpath)
8185 path = sourcefile->diskpath;
82 FILE *f = fopen(path, "r");
86 FILE *f = fopen(path, "rb");
8387 if (f) {
8488 fseek(f, 0, SEEK_END);
8589 int size = ftell(f);
318322 return delta;
319323 }
320324
321 void ohcount_sourcefile_set_filenames(SourceFile *sourcefile,
322 char **filenames) {
323 if (sourcefile->filenames) {
324 int i = 0;
325 while (sourcefile->filenames[i])
326 free(sourcefile->filenames[i++]);
327 free(sourcefile->filenames);
328 }
329
330 if (filenames != NULL) {
331 int length = 0;
332 while (filenames[length] != NULL) length++;
333 char **fnames = calloc(length + 1, sizeof(char *));
334
335 int i;
336 for (i = 0; i < length; i++) {
337 int len = strlen(filenames[i]);
338 char *fname = malloc(len + 1);
339 strncpy(fname, filenames[i], len);
340 fname[len] = '\0';
341 fnames[i] = fname;
342 }
343 sourcefile->filenames = fnames;
344 } else sourcefile->filenames = NULL;
345 }
346
347 char **ohcount_sourcefile_get_filenames(SourceFile *sourcefile) {
348 if (sourcefile->filenames == NULL) {
349 char dirpath[FILENAME_MAX];
350 strncpy(dirpath, sourcefile->filepath, sourcefile->dirpath);
351 dirpath[sourcefile->dirpath] = '\0';
352 struct dirent *file;
353 DIR *d = opendir((const char *)dirpath);
354 if (d) {
355 int length = 0;
356 while ((file = readdir(d))) length++;
357 closedir(d);
358
359 char **filenames = calloc(length + 1, sizeof(char *));
360 int i = 0;
361 d = opendir((const char *)dirpath);
362 while ((file = readdir(d))) {
363 int len = strlen(file->d_name);
364 char *filename = malloc(len + 1);
365 strncpy(filename, file->d_name, len);
366 filename[len] = '\0';
367 filenames[i++] = filename;
368 }
369 closedir(d);
370 sourcefile->filenames = filenames;
371 }
372 }
373 return sourcefile->filenames;
374 }
375
325 /* NOTE! Does not free sourcefile->filenames.
326 * Calling code is responsible for alloc+free of filenames.
327 */
376328 void ohcount_sourcefile_free(SourceFile *sourcefile) {
377329 free(sourcefile->filepath);
378330 if (sourcefile->diskpath)
385337 ohcount_license_list_free(sourcefile->license_list);
386338 if (sourcefile->loc_list)
387339 ohcount_loc_list_free(sourcefile->loc_list);
388 if (sourcefile->filenames) {
389 int i = 0;
390 while (sourcefile->filenames[i])
391 free(sourcefile->filenames[i++]);
392 free(sourcefile->filenames);
393 }
394340 free(sourcefile);
395341 }
396342
428374 char *f_p = filepath + strlen(directory) + 1;
429375
430376 struct dirent *file;
431 DIR *d = opendir(directory);
377 DIR *d = NULL;
378 d = opendir(directory);
432379 if (d) {
433380 while ((file = readdir(d))) {
381 struct stat st;
434382 int length = strlen(file->d_name);
435383 strncpy(f_p, (const char *)file->d_name, length);
436384 *(f_p + length) = '\0';
437385
438 if (file->d_type == DT_DIR && *file->d_name != '.') // no hidden dirs
386 lstat(filepath, &st);
387 if(S_ISLNK(st.st_mode))
388 continue;
389
390 if (S_ISDIR(st.st_mode) && *file->d_name != '.') // no hidden dirs
439391 ohcount_sourcefile_list_add_directory(list, filepath);
440 else if (file->d_type == DT_REG
441 #ifdef TMP_FILES_ARE_DT_UNKNOWN
442 || file->d_type == DT_UNKNOWN
443 #endif
444 )
392 else if (S_ISREG(st.st_mode))
445393 ohcount_sourcefile_list_add_file(list, filepath);
446394 }
447395 closedir(d);
448 ohcount_sourcefile_list_add_file(list, directory);
449396 }
450397 }
451398
154154 SourceFile *to);
155155
156156 /**
157 * Sets the given SourceFile's directory contents to the string array given.
158 * The given array is copied and may be 'free'd immediately.
159 * @param sourcefile A SourceFile created by ohcount_sourcefile_new().
160 * @param filenames String array of filenames. If NULL, the next call to
161 * ohcount_sourcefile_get_filenames will access the SourceFile's directory.
162 */
163 void ohcount_sourcefile_set_filenames(SourceFile *sourcefile,
164 char **filenames);
165
166 /**
167 * Returns a string array of the given SourceFile's directory contents.
168 * If the existing 'filenames' field is NULL, the directory is accessed and its
169 * listing is returned.
170 * The returned pointer and its contents are used internally and must not be
171 * 'free'd.
172 * @param sourcefile A SourceFile created by ohcount_sourcefile_new().
173 * @return pointer to a list of filenames (NULL-pointer terminated).
174 */
175 char **ohcount_sourcefile_get_filenames(SourceFile *sourcefile);
176
177 /**
178157 * Frees a SourceFile created by ohcount_sourcefile_new().
179158 * @param sourcefile A SourceFile created by ohcount_sourcefile_new().
180159 */
302302 */
303303 LocList *loc_list;
304304
305 /**
306 * A string array of all filenames in this file's directory.
307 * Do not use this field. Use ohcount_sourcefile_get_filenames() instead.
308 */
305 /** A string array of all filenames in this file's directory. */
309306 char **filenames;
310307
311308 } SourceFile;
0 <asx version="3.0">
1 <title>Example.com Live Stream</title>
2 <entry>
3 <title>Short Announcement to Play Before Main Stream</title>
4 <ref href="http://example.com/announcement.wma" />
5 </entry>
6 <entry>
7 <title>Example radio</title>
8 <ref href="http://example.com:8080" />
9 </entry>
10 </asx>
0 data;
1 param p := 42;
0 # An AMPL model
1 var x >= 42;
2 minimize o: x;
0 ; "Hello world" in 6502 assembly language for 8-bit Atari.
1 ; Assembler: http://xasm.atari.org/ or http://mads.atari8.info/
2
3 org $3000
4 main lda #$21
5 sta $22f
6 lda #<dl
7 sta $230
8 lda #>dl
9 sta $231
10 jmp *
11
12 text dta d' HELLO, ',d'WORLD! '*
13
14 ; Display List
15 dl dta b($70),b($70),b($70),b($47),a(text),b($41),a(dl)
16
17 org $2e0
18 dta a(main)
19
20 end
0 /*
1 * WebSoy - Client for OSX
2 * Copyright (C) 2011,2012 Copyleft Games Group
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as published
6 * by the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
13 *
14 * You should have received a copy of the GNU Affero General Public License
15 * along with this program; if not, see http://www.gnu.org/licenses
16 *
17 */
18
19 #if XP_MACOSX
20
21 [indent=4]
22 uses
23 GLib
24 GL
25
26 class Client : Object
27 scene : soy.scenes.Scene
28 window : soy.widgets.Window
29
30 construct (window : NP.Window)
31 self.scene = new soy.scenes.Scene()
32 self.window = new soy.widgets.Window(null)
33
34 // TODO
35
36 #endif
37
0 Require Import String.
1 (* comment *)
2 Check "multiline
3 string"%string.
4
5 (* multiline
6 comment *)
7
8 (* recursion in (* a
9 comment *) to complicate things *)
0 /* -*- mode: C; -*-
1 * The upper-case "C" mode should be interpreted as straight C, not C++ */
(New empty file)
(New empty file)
+0
-5
test/detect_files/foo.R less more
0 dummy<-function() {
1 # A dummy function to test the R language parser.
2 1.0
3 }
4
0 >++++++[>+++[<<++++>>-]<-]<.
1 >+++++[<++++++>-]<-.
2 +++++++.
3 .
4 +++.
5 >>++++[<++++++>-]<++[<--->-]<-.
6 >>++[<+++++>-]<+[<+++++>-]<.
7 >++++[<++++++>-]<.
8 +++.
9 ------.
10 >++[<---->-]<.
11 >>++[<+++++>-]<+[<------>-]<-.
12 .
13 .
14 .
15 .
0 = comment
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 = Try to open b file
34 >+++++++[>+++++++[<<++>>-]<-]<.
35 #[
36 >>++++[<++++>-]<+[<++++++>-]<.
37 +++.
38 +++.
39 -------.
40 >>++++[<++++++>-]<-[<--->-]<.
41 >>++[<+++++>-]<+[<++++++>-]<.
42 >>++[<+++++>-]<+[<------>-]<.
43 >>++++[<++++++>-]<++[<+++>-]<+.
44 +.
45 >++[<----->-]<-.
46 >+++[<+++>-]<.
47 >+++[<--->-]<.
48 -.
49 #]
0 //ChaiScript file
1 def dosomething()
2 {
3 }
0 # CoffeeScript sample
1 square = (x) -> x * x
0 \begin{document}
1 \texbf Hello world
2
3
4 % \acommand
5 % \anothercommand
6 %% sample comment
7
8 \end{document}
0 import "ecere"
1
2 class HelloForm : Window
3 {
4 text = "My First eC Application";
5 borderStyle = sizable;
6 size = { 280, 100 };
7 hasClose = true;
8
9 Label label
10 {
11 this, position = { 10, 10 }, font = { "Arial", 30 },
12 text = "Hello, World!!"
13 };
14 };
15
16 HelloForm hello { };
0 /* A Bison parser, made by GNU Bison 2.0. */
1
2 /* Skeleton parser for Yacc-like parsing with Bison,
3 Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
8 any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA. */
19
20 /* As a special exception, when this file is copied by Bison into a
21 Bison output file, you may use that output file without restriction.
22 This special exception was added by the Free Software Foundation
23 in version 1.24 of Bison. */
24
25 /* Tokens. */
26 #ifndef YYTOKENTYPE
27 # define YYTOKENTYPE
28 /* Put the tokens into the symbol table, so that GDB and other debuggers
29 know about them. */
30 enum yytokentype {
31 IDENTIFIER = 258,
32 CONSTANT = 259,
33 STRING_LITERAL = 260,
34 SIZEOF = 261,
35 PTR_OP = 262,
36 INC_OP = 263,
37 DEC_OP = 264,
38 LEFT_OP = 265,
39 RIGHT_OP = 266,
40 LE_OP = 267,
41 GE_OP = 268,
42 EQ_OP = 269,
43 NE_OP = 270,
44 AND_OP = 271,
45 OR_OP = 272,
46 MUL_ASSIGN = 273,
47 DIV_ASSIGN = 274,
48 MOD_ASSIGN = 275,
49 ADD_ASSIGN = 276,
50 SUB_ASSIGN = 277,
51 LEFT_ASSIGN = 278,
52 RIGHT_ASSIGN = 279,
53 AND_ASSIGN = 280,
54 XOR_ASSIGN = 281,
55 OR_ASSIGN = 282,
56 TYPE_NAME = 283,
57 TYPEDEF = 284,
58 EXTERN = 285,
59 STATIC = 286,
60 AUTO = 287,
61 REGISTER = 288,
62 CHAR = 289,
63 SHORT = 290,
64 INT = 291,
65 UINT = 292,
66 INT64 = 293,
67 LONG = 294,
68 SIGNED = 295,
69 UNSIGNED = 296,
70 FLOAT = 297,
71 DOUBLE = 298,
72 CONST = 299,
73 VOLATILE = 300,
74 VOID = 301,
75 VALIST = 302,
76 STRUCT = 303,
77 UNION = 304,
78 ENUM = 305,
79 ELLIPSIS = 306,
80 CASE = 307,
81 DEFAULT = 308,
82 IF = 309,
83 SWITCH = 310,
84 WHILE = 311,
85 DO = 312,
86 FOR = 313,
87 GOTO = 314,
88 CONTINUE = 315,
89 BREAK = 316,
90 RETURN = 317,
91 IFX = 318,
92 ELSE = 319,
93 CLASS = 320,
94 THISCLASS = 321,
95 CLASS_NAME = 322,
96 PROPERTY = 323,
97 SETPROP = 324,
98 GETPROP = 325,
99 NEWOP = 326,
100 RENEW = 327,
101 DELETE = 328,
102 EXT_DECL = 329,
103 EXT_STORAGE = 330,
104 IMPORT = 331,
105 DEFINE = 332,
106 VIRTUAL = 333,
107 EXT_ATTRIB = 334,
108 PUBLIC = 335,
109 PRIVATE = 336,
110 TYPED_OBJECT = 337,
111 ANY_OBJECT = 338,
112 _INCREF = 339,
113 EXTENSION = 340,
114 ASM = 341,
115 TYPEOF = 342,
116 WATCH = 343,
117 STOPWATCHING = 344,
118 FIREWATCHERS = 345,
119 WATCHABLE = 346,
120 CLASS_DESIGNER = 347,
121 CLASS_NO_EXPANSION = 348,
122 CLASS_FIXED = 349,
123 ISPROPSET = 350,
124 CLASS_DEFAULT_PROPERTY = 351,
125 PROPERTY_CATEGORY = 352,
126 CLASS_DATA = 353,
127 CLASS_PROPERTY = 354,
128 SUBCLASS = 355,
129 NAMESPACE = 356,
130 NEW0OP = 357,
131 RENEW0 = 358,
132 VAARG = 359,
133 DBTABLE = 360,
134 DBFIELD = 361,
135 DBINDEX = 362,
136 DATABASE_OPEN = 363
137 };
138 #endif
139 #define IDENTIFIER 258
140 #define CONSTANT 259
141 #define STRING_LITERAL 260
142 #define SIZEOF 261
143 #define PTR_OP 262
144 #define INC_OP 263
145 #define DEC_OP 264
146 #define LEFT_OP 265
147 #define RIGHT_OP 266
148 #define LE_OP 267
149 #define GE_OP 268
150 #define EQ_OP 269
151 #define NE_OP 270
152 #define AND_OP 271
153 #define OR_OP 272
154 #define MUL_ASSIGN 273
155 #define DIV_ASSIGN 274
156 #define MOD_ASSIGN 275
157 #define ADD_ASSIGN 276
158 #define SUB_ASSIGN 277
159 #define LEFT_ASSIGN 278
160 #define RIGHT_ASSIGN 279
161 #define AND_ASSIGN 280
162 #define XOR_ASSIGN 281
163 #define OR_ASSIGN 282
164 #define TYPE_NAME 283
165 #define TYPEDEF 284
166 #define EXTERN 285
167 #define STATIC 286
168 #define AUTO 287
169 #define REGISTER 288
170 #define CHAR 289
171 #define SHORT 290
172 #define INT 291
173 #define UINT 292
174 #define INT64 293
175 #define LONG 294
176 #define SIGNED 295
177 #define UNSIGNED 296
178 #define FLOAT 297
179 #define DOUBLE 298
180 #define CONST 299
181 #define VOLATILE 300
182 #define VOID 301
183 #define VALIST 302
184 #define STRUCT 303
185 #define UNION 304
186 #define ENUM 305
187 #define ELLIPSIS 306
188 #define CASE 307
189 #define DEFAULT 308
190 #define IF 309
191 #define SWITCH 310
192 #define WHILE 311
193 #define DO 312
194 #define FOR 313
195 #define GOTO 314
196 #define CONTINUE 315
197 #define BREAK 316
198 #define RETURN 317
199 #define IFX 318
200 #define ELSE 319
201 #define CLASS 320
202 #define THISCLASS 321
203 #define CLASS_NAME 322
204 #define PROPERTY 323
205 #define SETPROP 324
206 #define GETPROP 325
207 #define NEWOP 326
208 #define RENEW 327
209 #define DELETE 328
210 #define EXT_DECL 329
211 #define EXT_STORAGE 330
212 #define IMPORT 331
213 #define DEFINE 332
214 #define VIRTUAL 333
215 #define EXT_ATTRIB 334
216 #define PUBLIC 335
217 #define PRIVATE 336
218 #define TYPED_OBJECT 337
219 #define ANY_OBJECT 338
220 #define _INCREF 339
221 #define EXTENSION 340
222 #define ASM 341
223 #define TYPEOF 342
224 #define WATCH 343
225 #define STOPWATCHING 344
226 #define FIREWATCHERS 345
227 #define WATCHABLE 346
228 #define CLASS_DESIGNER 347
229 #define CLASS_NO_EXPANSION 348
230 #define CLASS_FIXED 349
231 #define ISPROPSET 350
232 #define CLASS_DEFAULT_PROPERTY 351
233 #define PROPERTY_CATEGORY 352
234 #define CLASS_DATA 353
235 #define CLASS_PROPERTY 354
236 #define SUBCLASS 355
237 #define NAMESPACE 356
238 #define NEW0OP 357
239 #define RENEW0 358
240 #define VAARG 359
241 #define DBTABLE 360
242 #define DBFIELD 361
243 #define DBINDEX 362
244 #define DATABASE_OPEN 363
245
246
247
248
249 #if ! defined (YYSTYPE) && ! defined (YYSTYPE_IS_DECLARED)
250 #line 42 "grammar.y"
251 typedef union YYSTYPE {
252 SpecifierType specifierType;
253 int i;
254 AccessMode declMode;
255 Identifier id;
256 Expression exp;
257 Specifier specifier;
258 OldList * list;
259 Enumerator enumerator;
260 Declarator declarator;
261 Pointer pointer;
262 Initializer initializer;
263 InitDeclarator initDeclarator;
264 TypeName typeName;
265 Declaration declaration;
266 Statement stmt;
267 FunctionDefinition function;
268 External external;
269 Context context;
270 AsmField asmField;
271
272 Instantiation instance;
273 MembersInit membersInit;
274 MemberInit memberInit;
275 ClassFunction classFunction;
276 ClassDefinition _class;
277 ClassDef classDef;
278 PropertyDef prop;
279 char * string;
280 Symbol symbol;
281 PropertyWatch propertyWatch;
282 TemplateParameter templateParameter;
283 TemplateArgument templateArgument;
284 TemplateDatatype templateDatatype;
285
286 DBTableEntry dbtableEntry;
287 DBIndexItem dbindexItem;
288 DBTableDef dbtableDef;
289 } YYSTYPE;
290 /* Line 1318 of yacc.c. */
291 #line 293 "grammar.eh"
292 # define yystype YYSTYPE /* obsolescent; will be withdrawn */
293 # define YYSTYPE_IS_DECLARED 1
294 # define YYSTYPE_IS_TRIVIAL 1
295 #endif
296
297 extern YYSTYPE yylval;
298
299 #if ! defined (YYLTYPE) && ! defined (YYLTYPE_IS_DECLARED)
300 typedef struct YYLTYPE
301 {
302 int first_line;
303 int first_column;
304 int last_line;
305 int last_column;
306 } YYLTYPE;
307 # define yyltype YYLTYPE /* obsolescent; will be withdrawn */
308 # define YYLTYPE_IS_DECLARED 1
309 # define YYLTYPE_IS_TRIVIAL 1
310 #endif
311
312 extern YYLTYPE yylloc;
313
314
0 % this is a Logtalk source file
1
2 :- object(hello_world).
3
4 % the initialization/1 directive argument is automatically executed
5 % when the object is loaded into memory:
6 :- initialization((nl, write('********** Hello World! **********'), nl)).
7
8 :- end_object.
0 ; No need for special content in here, detected by extension
0 ; No need for special content in here, detected by extension
0 import QtQuick 2.0
1
2 Rectangle {
3 width: 200
4 height: 200
5 color: "crimson"
6 }
0 # An AMPL script
1 print 42;
0 foo[x_] := b
1 (* a comment *)
0 #!/usr/bin/perl
1 print "Hello, world!\n";
0
1 # Also a Perl file but without the shebang line
2 print "Hello, world!\n";
0
1 % select(Element, List, Remaining)
2
3 select(H, [H| T], T).
4 select(H, [X| R], [X| T]) :-
5 select(H, R, T).
0 dummy<-function() {
1 # A dummy function to test the R language parser.
2 1.0
3 }
4
0 ; a rebol script
1 rebol []
2
3 ; A dummy function to test the REBOL language parser.
4 dummy: func [] [
5 read %blah
6 ]
0 ; a rebol script
1 REBOL []
2
3 ; A dummy function to test the REBOL language parser.
4 dummy: func [] [
5 read %blah
6 ]
0 \ Sample Forth code
1
2 ( This is a comment
3 spanning multiple lines )
4
5 : somedefinition ;
6
0 \ Sample Forth code
1
2 ( This is a comment
3 spanning multiple lines )
4
5 : somedefinition ;
6
00 ! -*- F90 -*-
1 program fortranfreecheck
2 ! Simple check. Not valid fixed form thanks to the continuation.
3 write(*,*) 2 + &
4 & 2
5 goto 22
1 program fortranfreecheck
2 ! Simple check. Not valid fixed form thanks to code starting in first column.
3 write(*,*) 2 + &
4 & 2
5 goto 22
66 22 write(*,*) 'bar'
7 end
7 end program fortranfreecheck
0 // Sample Grace code
1
2 import "parsers-test" as parsers
3
4 class exports {
5 def program = rule {codeSequence ~ rep(ws) ~ end}
6 }
0 // Sample Grace code
1 print "OK"
0 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
1 # a ruby script
2 File.open("blah") do |io|
3 a = io.read
4 end
0 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
1 'use strict';
2
3 require('./external/shelljs/make');
4 var builder = require('./external/builder/builder.js');
5 var crlfchecker = require('./external/crlfchecker/crlfchecker.js');
6 var path = require('path');
0 # Sample M4 file
1
2 AC_DEFUN([SAMPLE],[
3 AC_REQUIRE([ANOTHER_SAMPLE])
4 printf "$2" >> "$1"
5 ])
0 (* Modula-2 module *)
1 MODULE Hello;
2 FROM STextIO IMPORT WriteString;
3 BEGIN
4 WriteString("Hello World!");
5 END Hello.
0 EXPORTS
1 DllCanUnloadNow PRIVATE
2 DllGetClassObject PRIVATE
3 DllRegisterServer PRIVATE
4 DllUnregisterServer PRIVATE
0 #!%PERL%
1 % This is prolog code, but the shebang says perl, so we respect the shebang and choose perl.
2 Head :- Body.
0 # This is not prolog. Do not be confused by the smiley, which looks like a Prolog rule.
1 print "Hello, world :-)\n"
0 import "classes/*.pp"
1 import "definitions/*.pp"
0 puppet lcode import "classes/*.pp"
1 puppet lcode import "definitions/*.pp"
0 class main::sub {
1 include substuff
2 }
0 puppet lcode class main::sub {
1 puppet lcode include substuff
2 puppet lcode }
0 /**
1 * We could easily have a comment of significant length here at the top.
2 *
3 * It might well have a boilerplate copyright notice, which could go on for
4 * quite some lines.
5 *
6 * But as it is, this example is boring, containing merely a self-referential
7 * comment in that location.
8 */
9
10 #pragma version(1)
11 #pragma rs java_package_name(com.example.example.example.example.example)
12 #pragma stateFragment(parent)
13
14 #include "rs_foo.rsh"
15
16 static int panic = 0;
17
18 float away = 1.f;
19
20 typedef struct __attribute__((packed, aligned(4))) Foo {
21 } Foo_t;
22 Foo_t *foo;
23
24 rs_mesh gears;
25
26 /**
27 * This example is pretty poorly written, ain't it?
28 */
29 void warranty() {
30 with(pleasure);
31 }
0 /*
1 * This is the example given by www.rust-lang.org
2 */
3 // Line comments work too
4 fn main() {
5 let nums = [1, 2];
6 let noms = ["Tim", "Eston", "Aaron", "Ben"];
7
8 let mut odds = nums.iter().map(|&x| x * 2 - 1);
9
10 for num in odds {
11 do spawn {
12 println!("{:s} says hello from a lightweight thread!", noms[num]);
13 }
14 }
15 }
0 DEFINITION MODULE Sample; (* in Modula-2 *)
1
2 (* This is a comment *)
3
4 (* This is a comment ...
5 ... spanning more than one line *)
6
7 CONST
8 sqString = 'this is a string within "a string" ...';
9 dqString = "this is a string within 'a string' ...";
10
11 END Sample.
0 ampl comment /* This is a test file for AMPL
1 ampl comment * This is a multiline comment
2 ampl comment */
3 ampl blank
4 ampl comment # An AMPL model
5 ampl code var x >= 42; # variable definition.
6 ampl code minimize o: x;
0 assembler comment ; "Hello world" in 6502 assembly language for 8-bit Atari.
1 assembler comment ; Assembler: http://xasm.atari.org/ or http://mads.atari8.info/
2 assembler blank
3 assembler code org $3000
4 assembler code main lda #$21
5 assembler code sta $22f
6 assembler code lda #<dl
7 assembler code sta $230
8 assembler code lda #>dl
9 assembler code sta $231
10 assembler code jmp *
11 assembler blank
12 assembler code text dta d' HELLO, ',d'WORLD! '*
13 assembler blank
14 assembler comment ; Display List
15 assembler code dl dta b($70),b($70),b($70),b($47),a(text),b($41),a(dl)
16 assembler blank
17 assembler code org $2e0
18 assembler code dta a(main)
19 assembler blank
20 assembler code end
0 assembler comment ; "Hello world" in 6502 assembly language for 8-bit Atari.
1 assembler comment ; Assembler: http://xasm.atari.org/ or http://mads.atari8.info/
2 assembler blank
3 assembler code org $3000
4 assembler code main lda #$21
5 assembler code sta $22f
6 assembler code lda #<dl
7 assembler code sta $230
8 assembler code lda #>dl
9 assembler code sta $231
10 assembler code jmp *
11 assembler blank
12 assembler code text dta d' HELLO, ',d'WORLD! '*
13 assembler blank
14 assembler comment ; Display List
15 assembler code dl dta b($70),b($70),b($70),b($47),a(text),b($41),a(dl)
16 assembler blank
17 assembler code org $2e0
18 assembler code dta a(main)
19 assembler blank
20 assembler code end
0 augeas comment (** documentation *)
1 augeas code module Augeas =
2 augeas code autoload xfm
3 augeas comment (**/**)
4 augeas comment (* extra comment *)
5 augeas blank
6 augeas comment (* multiline
7 augeas comment comment*)
8 augeas code let lns = Shellvars.lns
9 augeas blank
10 augeas comment (* recursion in (* a
11 augeas comment comment *) to complicate things *)
12 augeas code let filter = incl "/foo/bar"
13 augeas code let xfm = transform lns filter
0 bfpp blank
1 bfpp comment = comment
2 bfpp code >++++++[>+++[<<++++>>-]<-]<.
3 bfpp code >+++++[<++++++>-]<-.
4 bfpp code +++++++.
5 bfpp code .
6 bfpp code +++.
7 bfpp code >>++++[<++++++>-]<++[<--->-]<-.
8 bfpp code >>++[<+++++>-]<+[<+++++>-]<.
9 bfpp code >++++[<++++++>-]<.
10 bfpp code +++.
11 bfpp code ------.
12 bfpp code >++[<---->-]<.
13 bfpp code >>++++[<++++>-]<+[<---->-]<.
14 bfpp code >+++++++[<++++++>-]<-.
15 bfpp code >++++++[<++++++>-]<+.
16 bfpp code >>++++[<++++++>-]<++[<--->-]<.
17 bfpp code >+++++[<+++++++>-]<-.
18 bfpp code >++++[>++++[<<+++>>-]<-]<.
19 bfpp code >++++[<---->-]<-.
20 bfpp code >++[<++++>-]<.
21 bfpp code +++++.
22 bfpp code >++[<---->-]<.
23 bfpp code >+++[<+++++>-]<.
24 bfpp code >+++[<------>-]<.
25 bfpp code >++[<++++>-]<.
26 bfpp code >++++[>++++[<<---->>-]<-]<.
27 bfpp code .
28 bfpp code >++[<----->-]<.
29 bfpp code .
30 bfpp code .
31 bfpp code .
32 bfpp code .
33 bfpp code [-]
34 bfpp comment = [-] is used to clear a cell
35 bfpp blank
36 bfpp comment = Try to open b file
37 bfpp code >+++++++[>+++++++[<<++>>-]<-]<.
38 bfpp code #[
39 bfpp code >>++++[<++++>-]<+[<++++++>-]<.
40 bfpp code +++.
41 bfpp code +++.
42 bfpp code -------.
43 bfpp code >>++++[<++++++>-]<-[<--->-]<.
44 bfpp code >>++[<+++++>-]<+[<++++++>-]<.
45 bfpp code >>++[<+++++>-]<+[<------>-]<.
46 bfpp code >>++++[<++++++>-]<++[<+++>-]<+.
47 bfpp code +.
48 bfpp code >++[<----->-]<-.
49 bfpp code >+++[<+++>-]<.
50 bfpp code >+++[<--->-]<.
51 bfpp code -.
52 bfpp code #]
53 bfpp code @include(nothing.bfpp)
00 bat comment REM comment 1
11 bat comment rem comment 2
22 bat comment rEm comment 3
3 bat comment rEm.comment 4
4 bat comment Rem=comment 5
5 bat comment @Rem comment 6
6 bat comment @reM=comment 7
7 bat comment ::comment 8
38 bat blank
49 bat code echo not a rem comment!
510 bat blank
0 brainfuck comment Print "Hello World!!!!!"
1 brainfuck blank
2 brainfuck code Line that does nothing: ><
3 brainfuck code >++++++[>+++[<<++++>>-]<-]<.
4 brainfuck code >+++++[<++++++>-]<-.
5 brainfuck code +++++++.
6 brainfuck code .
7 brainfuck code +++.
8 brainfuck code >>++++[<++++++>-]<++[<--->-]<-.
9 brainfuck code >>++[<+++++>-]<+[<+++++>-]<.
10 brainfuck code >++++[<++++++>-]<.
11 brainfuck code +++.
12 brainfuck code ------.
13 brainfuck code >++[<---->-]<.
14 brainfuck code >>++[<+++++>-]<+[<------>-]<-.
15 brainfuck code .
16 brainfuck code .
17 brainfuck code .
18 brainfuck code .
0 chaiscript comment /*
1 chaiscript comment Random Comments
2 chaiscript comment Foo Foo Foo
3 chaiscript comment */
4 chaiscript code var submenu=1;
5 chaiscript comment // comment
6 chaiscript comment // another comment
7 chaiscript code submenu += 10
8 chaiscript code var f = fun() { 5 };
9 chaiscript code def myFun(i) : i > 0 {
10 chaiscript code return i + 10;
11 chaiscript code }
12 chaiscript blank
13 chaiscript blank
14 chaiscript comment // some comment
15 chaiscript code var delay_hide=500
16 chaiscript code b=0
0 clojure comment ;;; Copyright (C) 2009 Brendan Ribera. All rights reserved.
1 clojure comment ;;; Distributed under the MIT License; see the file LICENSE
2 clojure comment ;;; at the root of this distribution.
3 clojure code (ns kdtree)
4 clojure blank
5 clojure code (defn dist-squared [a b]
6 clojure code "Compute the K-dimensional distance between two points"
7 clojure code (reduce + (for [i (range (count a))]
8 clojure code (let [v (- (nth a i)
9 clojure code (nth b i))]
10 clojure code (* v v)))))
11 clojure blank
12 clojure comment ;;; Simple accessors
13 clojure code (defn- node-value [n] (first n))
14 clojure code (defn- node-left [n] (first (rest n)))
15 clojure code (defn- node-right [n] (first (rest (rest n))))
0 cuda code #include <unistd.h>
1 cuda code #include <error.h>
2 cuda code #include <stdio.h>
3 cuda code #include <stdlib.h>
4 cuda code #include <errno.h>
5 cuda code #include <assert.h>
6 cuda blank
7 cuda code #include "components.h"
8 cuda code #include "common.h"
9 cuda blank
10 cuda code #define THREADS 256
11 cuda blank
12 cuda comment /* Store 3 RGB float components */
13 cuda code __device__ void storeComponents(float *d_r, float *d_g, float *d_b, float r, float g, float b, int pos)
14 cuda code {
15 cuda code d_r[pos] = (r/255.0f) - 0.5f;
16 cuda code d_g[pos] = (g/255.0f) - 0.5f;
17 cuda code d_b[pos] = (b/255.0f) - 0.5f;
18 cuda code }
19 cuda blank
20 cuda comment /* Store 3 RGB intege components */
21 cuda code __device__ void storeComponents(int *d_r, int *d_g, int *d_b, int r, int g, int b, int pos)
22 cuda code {
23 cuda code d_r[pos] = r - 128;
24 cuda code d_g[pos] = g - 128;
25 cuda code d_b[pos] = b - 128;
26 cuda code }
27 cuda blank
28 cuda comment /* Store float component */
29 cuda code __device__ void storeComponent(float *d_c, float c, int pos)
30 cuda code {
31 cuda code d_c[pos] = (c/255.0f) - 0.5f;
32 cuda code }
33 cuda blank
34 cuda comment /* Store integer component */
35 cuda code __device__ void storeComponent(int *d_c, int c, int pos)
36 cuda code {
37 cuda code d_c[pos] = c - 128;
38 cuda code }
39 cuda blank
40 cuda comment /* Copy img src data into three separated component buffers */
41 cuda code template<typename T>
42 cuda code __global__ void c_CopySrcToComponents(T *d_r, T *d_g, T *d_b,
43 cuda code unsigned char * d_src,
44 cuda code int pixels)
45 cuda code {
46 cuda code int x = threadIdx.x;
47 cuda code int gX = blockDim.x*blockIdx.x;
48 cuda blank
49 cuda code __shared__ unsigned char sData[THREADS*3];
50 cuda blank
51 cuda comment /* Copy data to shared mem by 4bytes other checks are not necessary, since d_src buffer is aligned to sharedDataSize */
52 cuda code if ( (x*4) < THREADS*3 ) {
53 cuda code float *s = (float *)d_src;
54 cuda code float *d = (float *)sData;
55 cuda code d[x] = s[((gX*3)>>2) + x];
56 cuda code }
57 cuda code __syncthreads();
58 cuda blank
59 cuda code T r, g, b;
60 cuda blank
61 cuda code int offset = x*3;
62 cuda code r = (T)(sData[offset]);
63 cuda code g = (T)(sData[offset+1]);
64 cuda code b = (T)(sData[offset+2]);
65 cuda blank
66 cuda code int globalOutputPosition = gX + x;
67 cuda code if (globalOutputPosition < pixels) {
68 cuda code storeComponents(d_r, d_g, d_b, r, g, b, globalOutputPosition);
69 cuda code }
70 cuda code }
71 cuda blank
72 cuda comment /* Copy img src data into three separated component buffers */
73 cuda code template<typename T>
74 cuda code __global__ void c_CopySrcToComponent(T *d_c, unsigned char * d_src, int pixels)
75 cuda code {
76 cuda code int x = threadIdx.x;
77 cuda code int gX = blockDim.x*blockIdx.x;
78 cuda blank
79 cuda code __shared__ unsigned char sData[THREADS];
80 cuda blank
81 cuda comment /* Copy data to shared mem by 4bytes other checks are not necessary, since d_src buffer is aligned to sharedDataSize */
82 cuda code if ( (x*4) < THREADS) {
83 cuda code float *s = (float *)d_src;
84 cuda code float *d = (float *)sData;
85 cuda code d[x] = s[(gX>>2) + x];
86 cuda code }
87 cuda code __syncthreads();
88 cuda blank
89 cuda code T c;
90 cuda blank
91 cuda code c = (T)(sData[x]);
92 cuda blank
93 cuda code int globalOutputPosition = gX + x;
94 cuda code if (globalOutputPosition < pixels) {
95 cuda code storeComponent(d_c, c, globalOutputPosition);
96 cuda code }
97 cuda code }
98 cuda blank
99 cuda blank
100 cuda comment /* Separate compoents of 8bit RGB source image */
101 cuda code template<typename T>
102 cuda code void rgbToComponents(T *d_r, T *d_g, T *d_b, unsigned char * src, int width, int height)
103 cuda code {
104 cuda code unsigned char * d_src;
105 cuda code int pixels = width*height;
106 cuda code int alignedSize = DIVANDRND(width*height, THREADS) * THREADS * 3; //aligned to thread block size -- THREADS
107 cuda blank
108 cuda comment /* Alloc d_src buffer */
109 cuda code cudaMalloc((void **)&d_src, alignedSize);
110 cuda code cudaCheckAsyncError("Cuda malloc")
111 cuda code cudaMemset(d_src, 0, alignedSize);
112 cuda blank
113 cuda comment /* Copy data to device */
114 cuda code cudaMemcpy(d_src, src, pixels*3, cudaMemcpyHostToDevice);
115 cuda code cudaCheckError("Copy data to device")
116 cuda blank
117 cuda comment /* Kernel */
118 cuda code dim3 threads(THREADS);
119 cuda code dim3 grid(alignedSize/(THREADS*3));
120 cuda code assert(alignedSize%(THREADS*3) == 0);
121 cuda code c_CopySrcToComponents<<<grid, threads>>>(d_r, d_g, d_b, d_src, pixels);
122 cuda code cudaCheckAsyncError("CopySrcToComponents kernel")
123 cuda blank
124 cuda comment /* Free Memory */
125 cuda code cudaFree(d_src);
126 cuda code cudaCheckAsyncError("Free memory")
127 cuda code }
128 cuda code template void rgbToComponents<float>(float *d_r, float *d_g, float *d_b, unsigned char * src, int width, int height);
129 cuda code template void rgbToComponents<int>(int *d_r, int *d_g, int *d_b, unsigned char * src, int width, int height);
130 cuda blank
131 cuda blank
132 cuda comment /* Copy a 8bit source image data into a color compoment of type T */
133 cuda code template<typename T>
134 cuda code void bwToComponent(T *d_c, unsigned char * src, int width, int height)
135 cuda code {
136 cuda code unsigned char * d_src;
137 cuda code int pixels = width*height;
138 cuda code int alignedSize = DIVANDRND(pixels, THREADS) * THREADS; //aligned to thread block size -- THREADS
139 cuda blank
140 cuda comment /* Alloc d_src buffer */
141 cuda code cudaMalloc((void **)&d_src, alignedSize);
142 cuda code cudaCheckAsyncError("Cuda malloc")
143 cuda code cudaMemset(d_src, 0, alignedSize);
144 cuda blank
145 cuda comment /* Copy data to device */
146 cuda code cudaMemcpy(d_src, src, pixels, cudaMemcpyHostToDevice);
147 cuda code cudaCheckError("Copy data to device")
148 cuda blank
149 cuda comment /* Kernel */
150 cuda code dim3 threads(THREADS);
151 cuda code dim3 grid(alignedSize/(THREADS));
152 cuda code assert(alignedSize%(THREADS) == 0);
153 cuda code c_CopySrcToComponent<<<grid, threads>>>(d_c, d_src, pixels);
154 cuda code cudaCheckAsyncError("CopySrcToComponent kernel")
155 cuda blank
156 cuda comment /* Free Memory */
157 cuda code cudaFree(d_src);
158 cuda code cudaCheckAsyncError("Free memory")
159 cuda code }
160 cuda blank
161 cuda code template void bwToComponent<float>(float *d_c, unsigned char *src, int width, int height);
162 cuda code template void bwToComponent<int>(int *d_c, unsigned char *src, int width, int height);
0 coq code Require Import String.
1 coq comment (* comment *)
2 coq code Check "multiline
3 coq code string"%string.
4 coq blank
5 coq comment (* multiline
6 coq comment comment *)
7 coq blank
8 coq comment (* recursion in (* a
9 coq comment comment *) to complicate things *)
0 qml comment // Just an example of QML file...
1 qml blank
2 qml code import QtQuick 2.0
3 qml blank
4 qml code Rectangle {
5 qml code width: 200
6 qml code height: 200
7 qml code color: "crimson"
8 qml blank
9 qml code MouseArea {
10 qml code anchors.fill: parent
11 qml code onClicked: {
12 qml comment // Was clicked
13 qml code Qt.quit();
14 qml code }
15 qml code }
16 qml code }
0 racket comment ;; language declaration commented out until someone extends the
1 racket comment ;; parser to support it:
2 racket blank
3 racket comment ;; #lang racket
4 racket blank
5 racket comment ;; Report each unique line from stdin
6 racket code (let ([saw (make-hash)])
7 racket code (for ([line (in-lines)])
8 racket code (unless (hash-ref saw line #f)
9 racket code (displayln line))
10 racket code (hash-set! saw line #t)))
11 racket blank
0 coffeescript comment # A CoffeeScript parser test file
1 coffeescript blank
2 coffeescript code simple_code = true
3 coffeescript blank
4 coffeescript comment ###
5 coffeescript comment A multi-line block comment
6 coffeescript comment begins and ends with three hash marks
7 coffeescript comment ###
8 coffeescript blank
9 coffeescript code multi_line_string = '''
10 coffeescript code A multi-line string constant ("here doc")
11 coffeescript code begins and ends with three quote marks
12 coffeescript code '''
13 coffeescript blank
14 coffeescript code foo = "A string can wrap across multiple lines
15 coffeescript code and may contain #{interpolated_values}"
16 coffeescript blank
17 coffeescript blank
18 coffeescript comment ###
19 coffeescript comment A clever parser can use Ohcount's "Polyglot" feature treat the
20 coffeescript comment following as embedded JavaScript.
21 coffeescript comment ###
22 javascript code embedded_js = `function() {
23 javascript code return [document.title, "Hello JavaScript"].join(": ");
24 coffeescript code }`
25 coffeescript blank
0 tex_dtx code \begin{document}
1 tex_dtx code \texbf Hello world
2 tex_dtx blank
3 tex_dtx blank
4 tex_dtx code % \acommand
5 tex_dtx code % \anothercommand
6 tex_dtx comment %% sample comment
7 tex_dtx blank
8 tex_dtx code \end{document}
0 nsis comment ; NSIS "header" libraries can be in .nsh files.
1 nsis comment /* Copyright some time
2 nsis comment * never
3 nsis comment * and not much of that either
4 nsis comment "still a comment"
5 nsis comment */
6 nsis blank
7 nsis code !macro SillyMacro Param1
8 nsis comment ; ... Because we can ;-)
9 nsis code !error "Why did you call this macro, ${Param1}? That was silly."
10 nsis code !macroend
11 nsis blank
12 nsis code Function Die
13 nsis comment # Likewise, because we can.
14 nsis code DetailPrint "Aarrrrggghh! I died."
15 nsis code Quit
16 nsis code FunctionEnd
0 nsis comment ; some nsis code
1 nsis comment /*
2 nsis comment * lorem
3 nsis comment ipsum
4 nsis comment dolor sit amet etcetera
5 nsis comment */
6 nsis blank
7 nsis code !include LogicLib.nsh
8 nsis code OutFile foo.exe
9 nsis blank
10 nsis code Section
11 nsis code IfFileExists ${__FILE__} 0 +2 ; comments can be inline
12 nsis comment # Use of ; in a string on the next line
13 nsis code MessageBox MB_OK "You moved this installer file; you shouldn't do that ;-)"
14 nsis code SectionEnd
0 forth comment \ Sample Forth code
1 forth blank
2 forth comment ( This is a comment
3 forth comment spanning multiple lines )
4 forth blank
5 forth code : somedefinition ;
6 forth blank
0 grace comment //////////////////////////////////////////////////
1 grace comment // Sample Grace code
2 grace blank
3 grace code import "parsers-test" as parsers
4 grace blank
5 grace code class exports {
6 grace code inherit parsers.exports
7 grace comment //BEGINGRAMMAR
8 grace comment // top level
9 grace code def program = rule {codeSequence ~ rep(ws) ~ end}
10 grace code def codeSequence = rule { repdel((declaration | statement | empty), semicolon) }
11 grace code def hashLine = rule { (symbol "#") ~ rep(anyChar | space) ~ (newLine | end) }
12 grace blank
13 grace comment // def comment =
14 grace blank
15 grace comment //def oldClassDeclaration = rule { classId ~ identifier ~ lBrace ~
16 grace comment // opt(genericFormals ~ blockFormals ~ arrow) ~ codeSequence ~ rBrace }
17 grace blank
18 grace code def typeOpExpression = rule { rep1sep(basicTypeExpression, typeOp) }
19 grace blank
20 grace code def typeOpExpression = rule {
21 grace code var otherOperator
22 grace code basicTypeExpression ~ opt(ws) ~
23 grace code opt( guard(typeOp, { s -> otherOperator:= s;
24 grace code true }) ~ rep1sep(basicTypeExpression ~ opt(ws),
25 grace code guard(typeOp, { s -> s == otherOperator })
26 grace code )
27 grace code )
28 grace code }
29 grace blank
30 grace comment // "literals"
31 grace code def literal = rule { stringLiteral | selfLiteral | blockLiteral | numberLiteral | objectLiteral | lineupLiteral | typeLiteral }
32 grace blank
33 grace comment // terminals
34 grace code def backslash = token "\\" // doesn't belong here, doesn't work if left below!
35 grace blank
36 grace code def colon = rule {both(symbol ":", not(assign))}
37 grace code def newLine = symbol "\n"
38 grace code def lParen = symbol "("
39 grace code def rParen = symbol ")"
40 grace blank
41 grace code def reservedOp = rule {assign | equals | dot | arrow | colon | semicolon} // this is not quite right
42 grace blank
43 grace comment //ENDGRAMMAR
44 grace code }
45 grace blank
0 logtalk comment /* test file for Logtalk parsing */
1 logtalk blank
2 logtalk comment % this is a Logtalk source file
3 logtalk blank
4 logtalk code :- object(hello_world).
5 logtalk blank
6 logtalk comment % the initialization/1 directive argument is automatically executed
7 logtalk comment % when the object is loaded into memory:
8 logtalk code :- initialization((nl, write('********** Hello World! **********'), nl)).
9 logtalk blank
10 logtalk code :- end_object.
0 mathematica blank
1 mathematica code SetEnhancedTimes[False];
2 mathematica code SetSourceLanguage["C"];
3 mathematica blank
4 mathematica comment (******************************************************************************)
5 mathematica comment (* Options *)
6 mathematica comment (******************************************************************************)
7 mathematica blank
8 mathematica code createCode[derivOrder_, useJacobian_, splitUpwindDerivs_, useVectors_, useOpenCL_, evolutionTimelevels_, addMatter_, formulation_] :=
9 mathematica code Module[{prefix, suffix, thorn},
10 mathematica blank
11 mathematica code prefix = "ML_";
12 mathematica code suffix =
13 mathematica code ""
14 mathematica code <> If [useJacobian, "_MP", ""]
15 mathematica code <> If [derivOrder!=4, "_O" <> ToString[derivOrder], ""]
16 mathematica code <> If [splitUpwindDerivs, "", "_UPW"]
17 mathematica code <> If [useVectors, "", "_NV"]
18 mathematica code <> If [useOpenCL, "_CL", ""]
19 mathematica comment (* <> If [evolutionTimelevels!=3, "_TL" <> ToString[evolutionTimelevels], ""] *)
20 mathematica comment (* <> If [addMatter==1, "_M", ""] *)
21 mathematica code ;
22 mathematica blank
23 mathematica code thorn = prefix <> formulation <> suffix;
24 mathematica blank
25 mathematica code SetAttributes[IfCCZ4, HoldAll];
26 mathematica code IfCCZ4[expr_, else_:Sequence[]] := If[formulation === "CCZ4", expr, Unevaluated[else]];
27 mathematica blank
28 mathematica comment (******************************************************************************)
29 mathematica comment (* Derivatives *)
30 mathematica comment (******************************************************************************)
31 mathematica blank
32 mathematica code KD = KroneckerDelta;
33 mathematica blank
34 mathematica code derivatives =
35 mathematica code {
36 mathematica code PDstandardNth[i_] -> StandardCenteredDifferenceOperator[1,fdOrder/2,i],
37 mathematica code PDstandardNth[i_,i_] -> StandardCenteredDifferenceOperator[2,fdOrder/2,i],
38 mathematica code PDstandardNth[i_,j_] -> StandardCenteredDifferenceOperator[1,fdOrder/2,i] *
39 mathematica code StandardCenteredDifferenceOperator[1,fdOrder/2,j],
40 mathematica code PDdissipationNth[i_] ->
41 mathematica code (-1)^(fdOrder/2) *
42 mathematica code spacing[i]^(fdOrder+1) / 2^(fdOrder+2) *
43 mathematica code StandardCenteredDifferenceOperator[fdOrder+2,fdOrder/2+1,i],
44 mathematica blank
45 mathematica comment (* PD: These come from my mathematica notebook
46 mathematica comment "Upwind-Kranc-Convert.nb" that converts upwinding finite
47 mathematica comment differencing operators generated by
48 mathematica comment StandardUpwindDifferenceOperator into this form *)
49 mathematica blank
50 mathematica code Sequence@@Flatten[Table[
51 mathematica code {PDupwindNth[i] -> Switch[fdOrder,
52 mathematica code 2, (dir[i]*(-3 + 4*shift[i]^dir[i] - shift[i]^(2*dir[i])))/(2*spacing[i]),
53 mathematica code 4, (dir[i]*(-10 - 3/shift[i]^dir[i] + 18*shift[i]^dir[i] -
54 mathematica code 6*shift[i]^(2*dir[i]) + shift[i]^(3*dir[i])))/(12*spacing[i]),
55 mathematica code 6, (dir[i]*(-35 + 2/shift[i]^(2*dir[i]) - 24/shift[i]^dir[i] + 80*shift[i]^dir[i] -
56 mathematica code 30*shift[i]^(2*dir[i]) + 8*shift[i]^(3*dir[i]) - shift[i]^(4*dir[i])))/(60*spacing[i]),
57 mathematica code 8, (dir[i]*(-378 - 5/shift[i]^(3*dir[i]) + 60/shift[i]^(2*dir[i]) - 420/shift[i]^dir[i] +
58 mathematica code 1050*shift[i]^dir[i] - 420*shift[i]^(2*dir[i]) + 140*shift[i]^(3*dir[i]) - 30*shift[i]^(4*dir[i]) +
59 mathematica code 3*shift[i]^(5*dir[i])))/(840*spacing[i])],
60 mathematica blank
61 mathematica code PDupwindNthAnti[i] -> Switch[fdOrder,
62 mathematica code 2, (+1 shift[i]^(-2) -4 shift[i]^(-1) +0 shift[i]^( 0) +4 shift[i]^(+1) -1 shift[i]^(+2)) / (4 spacing[i]),
63 mathematica code 4, (-1 shift[i]^(-3) +6 shift[i]^(-2) -21 shift[i]^(-1 )+0 shift[i]^( 0) +21 shift[i]^(+1)
64 mathematica code -6 shift[i]^(+2) +1 shift[i]^(+3)) / (24 spacing[i]),
65 mathematica code 6, (+1 shift[i]^(-4) -8 shift[i]^(-3) +32 shift[i]^(-2) -104 shift[i]^(-1) +0 shift[i]^( 0)
66 mathematica code +104 shift[i]^(+1) -32 shift[i]^(+2) +8 shift[i]^(+3) -1 shift[i]^(+4)) / (120 spacing[i]),
67 mathematica code 8, (-3 shift[i]^(-5) +30 shift[i]^(-4) -145 shift[i]^(-3) +480 shift[i]^(-2) -1470 shift[i]^(-1)
68 mathematica code +0 shift[i]^( 0) +1470 shift[i]^(+1) -480 shift[i]^(+2) +145 shift[i]^(+3) -30 shift[i]^(+4)
69 mathematica code +3 shift[i]^(+5)) / (1680 spacing[i])],
70 mathematica blank
71 mathematica code PDupwindNthSymm[i] -> Switch[fdOrder,
72 mathematica code 2, (-1 shift[i]^(-2) +4 shift[i]^(-1) -6 shift[i]^( 0) +4 shift[i]^(+1) -1 shift[i]^(+2)) / (4 spacing[i]),
73 mathematica code 4, (+1 shift[i]^(-3) -6 shift[i]^(-2) +15 shift[i]^(-1) -20 shift[i]^( 0) +15 shift[i]^(+1)
74 mathematica code -6 shift[i]^(+2) +1 shift[i]^(+3)) / (24 spacing[i]),
75 mathematica code 6, (-1 shift[i]^(-4) +8 shift[i]^(-3) - 28 shift[i]^(-2)+56 shift[i]^(-1)-70 shift[i]^( 0)
76 mathematica code +56 shift[i]^(+1) -28 shift[i]^(+2) +8 shift[i]^(+3) -1 shift[i]^(+4)) / (120 spacing[i]),
77 mathematica code 8, (+3 shift[i]^(-5) -30 shift[i]^(-4) +135 shift[i]^(-3) -360 shift[i]^(-2) +630 shift[i]^(-1)
78 mathematica code -756 shift[i]^( 0) +630 shift[i]^(+1) -360 shift[i]^(+2) +135 shift[i]^(+3) -30 shift[i]^(+4)
79 mathematica code +3 shift[i]^(+5)) / (1680 spacing[i])],
80 mathematica blank
81 mathematica comment (* TODO: make these higher order stencils *)
82 mathematica code PDonesided[i] -> dir[i] (-1 + shift[i]^dir[i]) / spacing[i]} /. i->j, {j,1,3}],1]
83 mathematica code };
84 mathematica blank
85 mathematica code PD = PDstandardNth;
86 mathematica code PDu = PDupwindNth;
87 mathematica code PDua = PDupwindNthAnti;
88 mathematica code PDus = PDupwindNthSymm;
89 mathematica comment (* PDo = PDonesided; *)
90 mathematica code PDdiss = PDdissipationNth;
91 mathematica blank
92 mathematica code If [splitUpwindDerivs,
93 mathematica code Upwind[dir_, var_, idx_] := dir PDua[var,idx] + Abs[dir] PDus[var,idx],
94 mathematica code Upwind[dir_, var_, idx_] := dir PDu[var,idx]];
95 mathematica blank
96 mathematica blank
97 mathematica blank
98 mathematica comment (******************************************************************************)
99 mathematica comment (* Tensors *)
100 mathematica comment (******************************************************************************)
101 mathematica blank
102 mathematica comment (* Register the tensor quantities with the TensorTools package *)
103 mathematica code Map [DefineTensor,
104 mathematica code {normal, tangentA, tangentB, dir,
105 mathematica code nn, nu, nlen, nlen2, su, vg,
106 mathematica code xx, rr, th, ph,
107 mathematica code admg, admK, admalpha, admdtalpha, admbeta, admdtbeta, H, M,
108 mathematica code g, detg, gu, G, R, trR, Km, trK, cdphi, cdphi2,
109 mathematica code phi, gt, At, Xt, Xtn, Theta, Z,
110 mathematica code alpha, A, beta, B, Atm, Atu, trA, Ats, trAts,
111 mathematica code dottrK, dotXt,
112 mathematica code cXt, cS, cA,
113 mathematica code e4phi, em4phi, ddetg, detgt, gtu, ddetgt, dgtu, ddgtu, Gtl, Gtlu, Gt,
114 mathematica code Rt, Rphi, gK,
115 mathematica code T00, T0, T, rho, S,
116 mathematica code x, y, z, r,
117 mathematica code epsdiss}];
118 mathematica blank
119 mathematica comment (* NOTE: It seems as if Lie[.,.] did not take these tensor weights
120 mathematica comment into account. Presumably, CD[.,.] and CDt[.,.] don't do this either. *)
121 mathematica code SetTensorAttribute[phi, TensorWeight, +1/6];
122 mathematica code SetTensorAttribute[gt, TensorWeight, -2/3];
123 mathematica code SetTensorAttribute[Xt, TensorWeight, +2/3];
124 mathematica code SetTensorAttribute[At, TensorWeight, -2/3];
125 mathematica code SetTensorAttribute[cXt, TensorWeight, +2/3];
126 mathematica code SetTensorAttribute[cS, TensorWeight, +2 ];
127 mathematica blank
128 mathematica code Map [AssertSymmetricIncreasing,
129 mathematica code {admg[la,lb], admK[la,lb], g[la,lb], K[la,lb], R[la,lb], cdphi2[la,lb],
130 mathematica code gt[la,lb], At[la,lb], Ats[la,lb], Rt[la,lb], Rphi[la,lb], T[la,lb]}];
131 mathematica code AssertSymmetricIncreasing [G[ua,lb,lc], lb, lc];
132 mathematica code AssertSymmetricIncreasing [Gtl[la,lb,lc], lb, lc];
133 mathematica code AssertSymmetricIncreasing [Gt[ua,lb,lc], lb, lc];
134 mathematica code AssertSymmetricIncreasing [gK[la,lb,lc], la, lb];
135 mathematica code Map [AssertSymmetricIncreasing,
136 mathematica code {gu[ua,ub], gtu[ua,ub], Atu[ua,ub]}];
137 mathematica code AssertSymmetricIncreasing [dgtu[ua,ub,lc], ua, ub];
138 mathematica code AssertSymmetricIncreasing [ddgtu[ua,ub,lc,ld], ua, ub];
139 mathematica code AssertSymmetricIncreasing [ddgtu[ua,ub,lc,ld], lc, ld];
140 mathematica blank
141 mathematica code DefineConnection [CD, PD, G];
142 mathematica code DefineConnection [CDt, PD, Gt];
143 mathematica blank
144 mathematica comment (* Use the CartGrid3D variable names *)
145 mathematica code x1=x; x2=y; x3=z;
146 mathematica blank
147 mathematica comment (* Use the ADMBase variable names *)
148 mathematica code admg11=gxx; admg12=gxy; admg22=gyy; admg13=gxz; admg23=gyz; admg33=gzz;
149 mathematica code admK11=kxx; admK12=kxy; admK22=kyy; admK13=kxz; admK23=kyz; admK33=kzz;
150 mathematica code admalpha=alp;
151 mathematica code admdtalpha=dtalp;
152 mathematica code admbeta1=betax; admbeta2=betay; admbeta3=betaz;
153 mathematica code admdtbeta1=dtbetax; admdtbeta2=dtbetay; admdtbeta3=dtbetaz;
154 mathematica blank
155 mathematica comment (* Use the TmunuBase variable names *)
156 mathematica code T00=eTtt;
157 mathematica code T01=eTtx; T02=eTty; T03=eTtz;
158 mathematica code T11=eTxx; T12=eTxy; T22=eTyy; T13=eTxz; T23=eTyz; T33=eTzz;
159 mathematica blank
160 mathematica blank
161 mathematica blank
162 mathematica comment (******************************************************************************)
163 mathematica comment (* Expressions *)
164 mathematica comment (******************************************************************************)
165 mathematica blank
166 mathematica comment (* enum constants for conformalMethod; these must be consistent
167 mathematica comment with the definition of the Cactus parameter conformalMethod *)
168 mathematica code CMphi = 0;
169 mathematica code CMW = 1;
170 mathematica blank
171 mathematica code detgExpr = Det [MatrixOfComponents [g [la,lb]]];
172 mathematica code ddetgExpr[la_] =
173 mathematica code Sum [D[Det[MatrixOfComponents[g[la, lb]]], X] PD[X, la],
174 mathematica code {X, Union[Flatten[MatrixOfComponents[g[la, lb]]]]}];
175 mathematica blank
176 mathematica code detgtExpr = Det [MatrixOfComponents [gt[la,lb]]];
177 mathematica code ddetgtExpr[la_] =
178 mathematica code Sum [D[Det[MatrixOfComponents[gt[la, lb]]], X] PD[X, la],
179 mathematica code {X, Union[Flatten[MatrixOfComponents[gt[la, lb]]]]}];
180 mathematica blank
181 mathematica code etaExpr = SpatialBetaDriverRadius / Max [r, SpatialBetaDriverRadius];
182 mathematica code thetaExpr = Min [Exp [1 - r / SpatialShiftGammaCoeffRadius], 1];
183 mathematica blank
184 mathematica blank
185 mathematica blank
186 mathematica comment (******************************************************************************)
187 mathematica comment (* Groups *)
188 mathematica comment (******************************************************************************)
189 mathematica blank
190 mathematica code evolvedGroups =
191 mathematica code {SetGroupName [CreateGroupFromTensor [phi ], prefix <> "log_confac"],
192 mathematica code SetGroupName [CreateGroupFromTensor [gt[la,lb]], prefix <> "metric" ],
193 mathematica code SetGroupName [CreateGroupFromTensor [Xt[ua] ], prefix <> "Gamma" ],
194 mathematica code SetGroupName [CreateGroupFromTensor [trK ], prefix <> "trace_curv"],
195 mathematica code SetGroupName [CreateGroupFromTensor [At[la,lb]], prefix <> "curv" ],
196 mathematica code SetGroupName [CreateGroupFromTensor [alpha ], prefix <> "lapse" ],
197 mathematica code SetGroupName [CreateGroupFromTensor [A ], prefix <> "dtlapse" ],
198 mathematica code SetGroupName [CreateGroupFromTensor [beta[ua] ], prefix <> "shift" ],
199 mathematica code SetGroupName [CreateGroupFromTensor [B[ua] ], prefix <> "dtshift" ],
200 mathematica code IfCCZ4[SetGroupName[CreateGroupFromTensor[Theta], prefix <> "Theta"]]};
201 mathematica code evaluatedGroups =
202 mathematica code {SetGroupName [CreateGroupFromTensor [H ], prefix <> "Ham"],
203 mathematica code SetGroupName [CreateGroupFromTensor [M[la] ], prefix <> "mom"],
204 mathematica code SetGroupName [CreateGroupFromTensor [cS ], prefix <> "cons_detg"],
205 mathematica code SetGroupName [CreateGroupFromTensor [cXt[ua]], prefix <> "cons_Gamma"],
206 mathematica code SetGroupName [CreateGroupFromTensor [cA ], prefix <> "cons_traceA"]};
207 mathematica blank
208 mathematica code declaredGroups = Join [evolvedGroups, evaluatedGroups];
209 mathematica code declaredGroupNames = Map [First, declaredGroups];
210 mathematica blank
211 mathematica blank
212 mathematica blank
213 mathematica code extraGroups =
214 mathematica code {{"grid::coordinates", {x, y, z, r}},
215 mathematica code {"ADMBase::metric", {gxx, gxy, gxz, gyy, gyz, gzz}},
216 mathematica code {"ADMBase::curv", {kxx, kxy, kxz, kyy, kyz, kzz}},
217 mathematica code {"ADMBase::lapse", {alp}},
218 mathematica code {"ADMBase::dtlapse", {dtalp}},
219 mathematica code {"ADMBase::shift", {betax, betay, betaz}},
220 mathematica code {"ADMBase::dtshift", {dtbetax, dtbetay, dtbetaz}},
221 mathematica code {"TmunuBase::stress_energy_scalar", {eTtt}},
222 mathematica code {"TmunuBase::stress_energy_vector", {eTtx, eTty, eTtz}},
223 mathematica code {"TmunuBase::stress_energy_tensor", {eTxx, eTxy, eTxz, eTyy, eTyz, eTzz}}
224 mathematica code };
225 mathematica blank
226 mathematica code groups = Join [declaredGroups, extraGroups];
227 mathematica blank
228 mathematica blank
229 mathematica blank
230 mathematica comment (******************************************************************************)
231 mathematica comment (* Initial data *)
232 mathematica comment (******************************************************************************)
233 mathematica blank
234 mathematica code initialCalc =
235 mathematica code {
236 mathematica code Name -> thorn <> "_Minkowski",
237 mathematica code Schedule -> {"IN ADMBase_InitialData"},
238 mathematica code ConditionalOnKeyword -> {"my_initial_data", "Minkowski"},
239 mathematica code Equations ->
240 mathematica code {
241 mathematica code phi -> IfThen[conformalMethod==CMW, 1, 0],
242 mathematica code gt[la,lb] -> KD[la,lb],
243 mathematica code trK -> 0,
244 mathematica code At[la,lb] -> 0,
245 mathematica code Xt[ua] -> 0,
246 mathematica code alpha -> 1,
247 mathematica code A -> 0,
248 mathematica code beta[ua] -> 0,
249 mathematica code B[ua] -> 0,
250 mathematica code IfCCZ4[Theta -> 0]
251 mathematica code }
252 mathematica code };
253 mathematica blank
254 mathematica blank
255 mathematica blank
256 mathematica comment (******************************************************************************)
257 mathematica comment (* Split a calculation *)
258 mathematica comment (******************************************************************************)
259 mathematica blank
260 mathematica code PartialCalculation[calc_, suffix_, updates_, evolVars_] :=
261 mathematica code Module[
262 mathematica code {name, calc1, replaces, calc2, vars, patterns, eqs, calc3},
263 mathematica comment (* Add suffix to name *)
264 mathematica code name = lookup[calc, Name] <> suffix;
265 mathematica code calc1 = mapReplace[calc, Name, name];
266 mathematica comment (* Replace some entries in the calculation *)
267 mathematica comment (* replaces = Map[Function[rule, mapReplace[#, rule[[1]], rule[[2]]]&], updates]; *)
268 mathematica code replaces = updates //. (lhs_ -> rhs_) -> (mapReplace[#, lhs, rhs]&);
269 mathematica code calc2 = Apply[Composition, replaces][calc1];
270 mathematica comment (* Remove unnecessary equations *)
271 mathematica code vars = Join[evolVars, lookup[calc2, Shorthands]];
272 mathematica code patterns = Replace[vars, { Tensor[n_,__] -> Tensor[n,__] ,
273 mathematica code dot[Tensor[n_,__]] -> dot[Tensor[n,__]]}, 1];
274 mathematica code eqs = FilterRules[lookup[calc, Equations], patterns];
275 mathematica code calc3 = mapReplace[calc2, Equations, eqs];
276 mathematica code calc3
277 mathematica code ];
278 mathematica blank
279 mathematica blank
280 mathematica blank
281 mathematica comment (******************************************************************************)
282 mathematica comment (* Convert from ADMBase *)
283 mathematica comment (******************************************************************************)
284 mathematica blank
285 mathematica code convertFromADMBaseCalc =
286 mathematica code {
287 mathematica code Name -> thorn <> "_convertFromADMBase",
288 mathematica code Schedule -> {"AT initial AFTER ADMBase_PostInitial"},
289 mathematica code ConditionalOnKeyword -> {"my_initial_data", "ADMBase"},
290 mathematica code Shorthands -> {g[la,lb], detg, gu[ua,ub], em4phi},
291 mathematica code Equations ->
292 mathematica code {
293 mathematica code g[la,lb] -> admg[la,lb],
294 mathematica code detg -> detgExpr,
295 mathematica code gu[ua,ub] -> 1/detg detgExpr MatrixInverse [g[ua,ub]],
296 mathematica blank
297 mathematica code phi -> IfThen[conformalMethod==CMW, detg^(-1/6), Log[detg]/12],
298 mathematica code em4phi -> IfThen[conformalMethod==CMW, phi^2, Exp[-4 phi]],
299 mathematica code gt[la,lb] -> em4phi g[la,lb],
300 mathematica blank
301 mathematica code trK -> gu[ua,ub] admK[la,lb],
302 mathematica code At[la,lb] -> em4phi (admK[la,lb] - (1/3) g[la,lb] trK),
303 mathematica blank
304 mathematica code alpha -> admalpha,
305 mathematica blank
306 mathematica code beta[ua] -> admbeta[ua],
307 mathematica blank
308 mathematica code IfCCZ4[Theta -> 0]
309 mathematica code }
310 mathematica code };
311 mathematica blank
312 mathematica code convertFromADMBaseGammaCalc =
313 mathematica code {
314 mathematica code Name -> thorn <> "_convertFromADMBaseGamma",
315 mathematica code Schedule -> {"AT initial AFTER " <> thorn <> "_convertFromADMBase"},
316 mathematica code ConditionalOnKeyword -> {"my_initial_data", "ADMBase"},
317 mathematica comment (*
318 mathematica comment Where -> InteriorNoSync,
319 mathematica comment *)
320 mathematica comment (* Do not synchronise right after this routine; instead, synchronise
321 mathematica comment after extrapolating *)
322 mathematica code Where -> Interior,
323 mathematica comment (* Synchronise after this routine, so that the refinement boundaries
324 mathematica comment are set correctly before extrapolating. (We will need to
325 mathematica comment synchronise again after extrapolating because extrapolation does
326 mathematica comment not fill ghost zones, but this is irrelevant here.) *)
327 mathematica code Shorthands -> {dir[ua],
328 mathematica code detgt, gtu[ua,ub], Gt[ua,lb,lc], theta},
329 mathematica code Equations ->
330 mathematica code {
331 mathematica code dir[ua] -> Sign[beta[ua]],
332 mathematica blank
333 mathematica code detgt -> 1 (* detgtExpr *),
334 mathematica code gtu[ua,ub] -> 1/detgt detgtExpr MatrixInverse [gt[ua,ub]],
335 mathematica code Gt[ua,lb,lc] -> 1/2 gtu[ua,ud]
336 mathematica code (PD[gt[lb,ld],lc] + PD[gt[lc,ld],lb] - PD[gt[lb,lc],ld]),
337 mathematica code Xt[ua] -> gtu[ub,uc] Gt[ua,lb,lc],
338 mathematica blank
339 mathematica comment (*
340 mathematica comment A -> - admdtalpha / (harmonicF alpha^harmonicN) (LapseAdvectionCoeff - 1),
341 mathematica comment *)
342 mathematica comment (* If LapseACoeff=0, then A is not evolved, in the sense that it
343 mathematica comment does not influence the time evolution of other variables. *)
344 mathematica code A -> IfThen [LapseACoeff != 0,
345 mathematica code 1 / (- harmonicF alpha^harmonicN)
346 mathematica code (+ admdtalpha
347 mathematica code - LapseAdvectionCoeff Upwind[beta[ua], alpha, la]),
348 mathematica code 0],
349 mathematica blank
350 mathematica code theta -> thetaExpr,
351 mathematica blank
352 mathematica comment (* If ShiftBCoeff=0 or theta ShiftGammaCoeff=0, then B^i is not
353 mathematica comment evolved, in the sense that it does not influence the time
354 mathematica comment evolution of other variables. *)
355 mathematica code B[ua] -> IfThen [ShiftGammaCoeff ShiftBCoeff != 0,
356 mathematica code 1 / (theta ShiftGammaCoeff)
357 mathematica code (+ admdtbeta[ua]
358 mathematica code - ShiftAdvectionCoeff Upwind[beta[ub], beta[ua], lb]),
359 mathematica code 0]
360 mathematica code }
361 mathematica code };
362 mathematica blank
363 mathematica comment (* Initialise the Gamma variables to 0. This is necessary with
364 mathematica comment multipatch because convertFromADMBaseGamma does not perform the
365 mathematica comment conversion in the boundary points, and the order in which symmetry
366 mathematica comment (interpatch) and outer boundary conditions is applied means that
367 mathematica comment points which are both interpatch and symmetry points are never
368 mathematica comment initialised. *)
369 mathematica code initGammaCalc =
370 mathematica code {
371 mathematica code Name -> thorn <> "_InitGamma",
372 mathematica code Schedule -> {"AT initial BEFORE " <> thorn <> "_convertFromADMBaseGamma"},
373 mathematica code ConditionalOnKeyword -> {"my_initial_data", "ADMBase"},
374 mathematica code Where -> Everywhere,
375 mathematica code Equations ->
376 mathematica code {
377 mathematica code Xt[ua] -> 0,
378 mathematica code A -> 0,
379 mathematica code B[ua] -> 0
380 mathematica code }
381 mathematica code };
382 mathematica blank
383 mathematica blank
384 mathematica blank
385 mathematica comment (******************************************************************************)
386 mathematica comment (* Convert to ADMBase *)
387 mathematica comment (******************************************************************************)
388 mathematica blank
389 mathematica code convertToADMBaseCalc =
390 mathematica code {
391 mathematica code Name -> thorn <> "_convertToADMBase",
392 mathematica code Schedule -> {"IN " <> thorn <> "_convertToADMBaseGroup"},
393 mathematica code Where -> Everywhere,
394 mathematica code Shorthands -> {e4phi},
395 mathematica code Equations ->
396 mathematica code {
397 mathematica code e4phi -> IfThen[conformalMethod==CMW, 1/phi^2, Exp[4 phi]],
398 mathematica code admg[la,lb] -> e4phi gt[la,lb],
399 mathematica code admK[la,lb] -> e4phi At[la,lb] + (1/3) admg[la,lb] trK,
400 mathematica code admalpha -> alpha,
401 mathematica code admbeta[ua] -> beta[ua]
402 mathematica code }
403 mathematica code };
404 mathematica blank
405 mathematica code convertToADMBaseDtLapseShiftCalc =
406 mathematica code {
407 mathematica code Name -> thorn <> "_convertToADMBaseDtLapseShift",
408 mathematica code Schedule -> {"IN " <> thorn <> "_convertToADMBaseGroup"},
409 mathematica code ConditionalOnKeyword -> {"dt_lapse_shift_method", "correct"},
410 mathematica code Where -> Interior,
411 mathematica code Shorthands -> {dir[ua], detgt, gtu[ua,ub], eta, theta},
412 mathematica code Equations ->
413 mathematica code {
414 mathematica code dir[ua] -> Sign[beta[ua]],
415 mathematica blank
416 mathematica code detgt -> 1 (* detgtExpr *),
417 mathematica comment (* This leads to simpler code... *)
418 mathematica code gtu[ua,ub] -> 1/detgt detgtExpr MatrixInverse [gt[ua,ub]],
419 mathematica blank
420 mathematica code eta -> etaExpr,
421 mathematica code theta -> thetaExpr,
422 mathematica blank
423 mathematica comment (* see RHS *)
424 mathematica comment (*
425 mathematica comment admdtalpha -> - harmonicF alpha^harmonicN
426 mathematica comment ((1 - LapseAdvectionCoeff) A + LapseAdvectionCoeff trK)
427 mathematica comment + LapseAdvectionCoeff beta[ua] PDu[alpha,la],
428 mathematica comment *)
429 mathematica code admdtalpha -> - harmonicF alpha^harmonicN
430 mathematica code (+ LapseACoeff A
431 mathematica code + ((1 - LapseACoeff)
432 mathematica code (trK - IfCCZ4[2 Theta, 0])))
433 mathematica code + LapseAdvectionCoeff Upwind[beta[ua], alpha, la],
434 mathematica code admdtbeta[ua] -> IfThen[harmonicShift,
435 mathematica code - 1/2 gtu[ua,uj] phi alpha
436 mathematica code (- 2 alpha PD[phi,lj]
437 mathematica code + 2 phi PD[alpha,lj]
438 mathematica code + gtu[uk,ul] phi alpha
439 mathematica code (PD[gt[lk,ll],lj] - 2 PD[gt[lj,lk],ll])),
440 mathematica comment (* else *)
441 mathematica code + theta ShiftGammaCoeff
442 mathematica code (+ ShiftBCoeff B[ua]
443 mathematica code + (1 - ShiftBCoeff)
444 mathematica code (Xt[ua] - eta BetaDriver beta[ua]))]
445 mathematica code + ShiftAdvectionCoeff Upwind[beta[ub], beta[ua], lb]
446 mathematica code }
447 mathematica code };
448 mathematica blank
449 mathematica code convertToADMBaseDtLapseShiftBoundaryCalc =
450 mathematica code {
451 mathematica code Name -> thorn <> "_convertToADMBaseDtLapseShiftBoundary",
452 mathematica code Schedule -> {"IN " <> thorn <> "_convertToADMBaseGroup"},
453 mathematica code ConditionalOnKeyword -> {"dt_lapse_shift_method", "correct"},
454 mathematica code Where -> BoundaryWithGhosts,
455 mathematica code Shorthands -> {detgt, gtu[ua,ub], eta, theta},
456 mathematica code Equations ->
457 mathematica code {
458 mathematica code detgt -> 1 (* detgtExpr *),
459 mathematica comment (* This leads to simpler code... *)
460 mathematica code gtu[ua,ub] -> 1/detgt detgtExpr MatrixInverse [gt[ua,ub]],
461 mathematica blank
462 mathematica code eta -> etaExpr,
463 mathematica code theta -> thetaExpr,
464 mathematica blank
465 mathematica comment (* see RHS, but omit derivatives near the boundary *)
466 mathematica comment (*
467 mathematica comment admdtalpha -> - harmonicF alpha^harmonicN
468 mathematica comment ((1 - LapseAdvectionCoeff) A + LapseAdvectionCoeff trK),
469 mathematica comment *)
470 mathematica code admdtalpha -> - harmonicF alpha^harmonicN
471 mathematica code (+ LapseACoeff A
472 mathematica code + ((1 - LapseACoeff)
473 mathematica code (trK - IfCCZ4[2 Theta, 0]))),
474 mathematica code admdtbeta[ua] -> IfThen[harmonicShift,
475 mathematica code 0,
476 mathematica comment (* else *)
477 mathematica code + theta ShiftGammaCoeff
478 mathematica code (+ ShiftBCoeff B[ua]
479 mathematica code + (1 - ShiftBCoeff)
480 mathematica code (Xt[ua] - eta BetaDriver beta[ua]))]
481 mathematica code }
482 mathematica code };
483 mathematica blank
484 mathematica code convertToADMBaseFakeDtLapseShiftCalc =
485 mathematica code {
486 mathematica code Name -> thorn <> "_convertToADMBaseFakeDtLapseShift",
487 mathematica code Schedule -> {"IN " <> thorn <> "_convertToADMBaseGroup"},
488 mathematica code ConditionalOnKeyword -> {"dt_lapse_shift_method", "noLapseShiftAdvection"},
489 mathematica code Where -> Everywhere,
490 mathematica code Shorthands -> {detgt, gtu[ua,ub], eta, theta},
491 mathematica code Equations ->
492 mathematica code {
493 mathematica code detgt -> 1 (* detgtExpr *),
494 mathematica comment (* This leads to simpler code... *)
495 mathematica code gtu[ua,ub] -> 1/detgt detgtExpr MatrixInverse [gt[ua,ub]],
496 mathematica blank
497 mathematica code eta -> etaExpr,
498 mathematica code theta -> thetaExpr,
499 mathematica blank
500 mathematica comment (* see RHS, but omit derivatives everywhere (which is wrong, but
501 mathematica comment faster, since it does not require synchronisation or boundary
502 mathematica comment conditions) *)
503 mathematica comment (*
504 mathematica comment admdtalpha -> - harmonicF alpha^harmonicN
505 mathematica comment ((1 - LapseAdvectionCoeff) A + LapseAdvectionCoeff trK),
506 mathematica comment *)
507 mathematica code admdtalpha -> - harmonicF alpha^harmonicN
508 mathematica code (+ LapseACoeff A
509 mathematica code + ((1 - LapseACoeff)
510 mathematica code (trK - IfCCZ4[2 Theta, 0]))),
511 mathematica code admdtbeta[ua] -> IfThen[harmonicShift,
512 mathematica code 0,
513 mathematica comment (* else *)
514 mathematica code + theta ShiftGammaCoeff
515 mathematica code (+ ShiftBCoeff B[ua]
516 mathematica code + (1 - ShiftBCoeff)
517 mathematica code (Xt[ua] - eta BetaDriver beta[ua]))]
518 mathematica code }
519 mathematica code };
520 mathematica blank
521 mathematica comment (******************************************************************************)
522 mathematica comment (* Evolution equations *)
523 mathematica comment (******************************************************************************)
524 mathematica blank
525 mathematica code evolCalc =
526 mathematica code {
527 mathematica code Name -> thorn <> "_RHS",
528 mathematica code Schedule -> {"IN " <> thorn <> "_evolCalcGroup"},
529 mathematica comment (*
530 mathematica comment Where -> Interior,
531 mathematica comment *)
532 mathematica comment (* Synchronise the RHS grid functions after this routine, so that
533 mathematica comment the refinement boundaries are set correctly before applying the
534 mathematica comment radiative boundary conditions. *)
535 mathematica code Where -> InteriorNoSync,
536 mathematica code ConditionalOnKeyword -> {"RHS_split", "combined"},
537 mathematica code Shorthands -> {dir[ua],
538 mathematica code detgt, gtu[ua,ub],
539 mathematica code Gt[ua,lb,lc], Gtl[la,lb,lc], Gtlu[la,lb,uc], Xtn[ua],
540 mathematica code Rt[la,lb], Rphi[la,lb], R[la,lb],
541 mathematica code Atm[ua,lb], Atu[ua,ub],
542 mathematica code e4phi, em4phi, cdphi[la], cdphi2[la,lb], g[la,lb], detg,
543 mathematica code gu[ua,ub], Ats[la,lb], trAts, eta, theta,
544 mathematica code rho, S[la], trS, fac1, fac2, dottrK, dotXt[ua],
545 mathematica code epsdiss[ua], IfCCZ4[Z[ua]], IfCCZ4[dotTheta]},
546 mathematica code Equations ->
547 mathematica code {
548 mathematica code dir[ua] -> Sign[beta[ua]],
549 mathematica blank
550 mathematica code detgt -> 1 (* detgtExpr *),
551 mathematica blank
552 mathematica comment (* This leads to simpler code... *)
553 mathematica code gtu[ua,ub] -> 1/detgt detgtExpr MatrixInverse [gt[ua,ub]],
554 mathematica code Gtl[la,lb,lc] -> 1/2
555 mathematica code (PD[gt[lb,la],lc] + PD[gt[lc,la],lb] - PD[gt[lb,lc],la]),
556 mathematica code Gtlu[la,lb,uc] -> gtu[uc,ud] Gtl[la,lb,ld],
557 mathematica code Gt[ua,lb,lc] -> gtu[ua,ud] Gtl[ld,lb,lc],
558 mathematica blank
559 mathematica comment (* The conformal connection functions calculated from the conformal metric,
560 mathematica comment used instead of Xt where no derivatives of Xt are taken *)
561 mathematica code Xtn[ui] -> gtu[uj,uk] Gt[ui,lj,lk],
562 mathematica blank
563 mathematica code e4phi -> IfThen[conformalMethod==CMW, 1/phi^2, Exp[4 phi]],
564 mathematica code em4phi -> 1 / e4phi,
565 mathematica code g[la,lb] -> e4phi gt[la,lb],
566 mathematica code detg -> detgExpr,
567 mathematica code gu[ua,ub] -> em4phi gtu[ua,ub],
568 mathematica blank
569 mathematica comment (* The Z quantities *)
570 mathematica comment (* gr-qc:1106.2254 (2011), eqn. (23) *)
571 mathematica code IfCCZ4[
572 mathematica code Z[ud] -> (1/2) gu[ua,ud] (- PD[gt[la,lb],lc] gtu[ub,uc] + gt[la,lc] Xt[uc])
573 mathematica code ],
574 mathematica blank
575 mathematica comment (* PRD 62, 044034 (2000), eqn. (18) *)
576 mathematica comment (* Adding Z term by changing Xtn to Xt *)
577 mathematica code Rt[li,lj] -> - (1/2) gtu[ul,um] PD[gt[li,lj],ll,lm]
578 mathematica code + (1/2) gt[lk,li] PD[Xt[uk],lj]
579 mathematica code + (1/2) gt[lk,lj] PD[Xt[uk],li]
580 mathematica code + (1/2) Xtn[uk] Gtl[li,lj,lk]
581 mathematica code + (1/2) Xtn[uk] Gtl[lj,li,lk]
582 mathematica code + (+ Gt[uk,li,ll] Gtlu[lj,lk,ul]
583 mathematica code + Gt[uk,lj,ll] Gtlu[li,lk,ul]
584 mathematica code + Gt[uk,li,ll] Gtlu[lk,lj,ul]),
585 mathematica blank
586 mathematica code fac1 -> IfThen[conformalMethod==CMW, -1/(2 phi), 1],
587 mathematica code cdphi[la] -> fac1 CDt[phi,la],
588 mathematica code fac2 -> IfThen[conformalMethod==CMW, 1/(2 phi^2), 0],
589 mathematica code cdphi2[la,lb] -> fac1 CDt[phi,la,lb] + fac2 CDt[phi,la] CDt[phi,lb],
590 mathematica blank
591 mathematica comment (* PRD 62, 044034 (2000), eqn. (15) *)
592 mathematica code Rphi[li,lj] -> - 2 cdphi2[lj,li]
593 mathematica code - 2 gt[li,lj] gtu[ul,un] cdphi2[ll,ln]
594 mathematica code + 4 cdphi[li] cdphi[lj]
595 mathematica code - 4 gt[li,lj] gtu[ul,un] cdphi[ln] cdphi[ll],
596 mathematica blank
597 mathematica code Atm[ua,lb] -> gtu[ua,uc] At[lc,lb],
598 mathematica code Atu[ua,ub] -> Atm[ua,lc] gtu[ub,uc],
599 mathematica blank
600 mathematica code R[la,lb] -> Rt[la,lb] + Rphi[la,lb],
601 mathematica code IfCCZ4[
602 mathematica code R[la,lb] -> R[la,lb] + (2/phi) (+ g[la,lc] Z[uc] PD[phi,lb]
603 mathematica code + g[lb,lc] Z[uc] PD[phi,la] - g[la,lb] Z[uc] PD[phi,lc])
604 mathematica code + e4phi Z[uc] PD[gt[la,lb],lc]
605 mathematica code ],
606 mathematica blank
607 mathematica comment (* Matter terms *)
608 mathematica blank
609 mathematica comment (* rho = n^a n^b T_ab *)
610 mathematica code rho -> addMatter
611 mathematica code (1/alpha^2 (T00 - 2 beta[ui] T0[li] + beta[ui] beta[uj] T[li,lj])),
612 mathematica blank
613 mathematica comment (* S_i = -p^a_i n^b T_ab, where p^a_i = delta^a_i + n^a n_i *)
614 mathematica code S[li] -> addMatter (-1/alpha (T0[li] - beta[uj] T[li,lj])),
615 mathematica blank
616 mathematica comment (* trS = gamma^ij T_ij *)
617 mathematica code trS -> addMatter (em4phi gtu[ui,uj] T[li,lj]),
618 mathematica blank
619 mathematica comment (* RHS terms *)
620 mathematica blank
621 mathematica comment (* PRD 62, 044034 (2000), eqn. (10) *)
622 mathematica comment (* PRD 67 084023 (2003), eqn. (16) and (23) *)
623 mathematica code dot[phi] -> IfThen[conformalMethod==CMW, 1/3 phi, -1/6]
624 mathematica code (alpha trK - PD[beta[ua],la]),
625 mathematica blank
626 mathematica comment (* PRD 62, 044034 (2000), eqn. (9) *)
627 mathematica comment (* gr-qc:1106.2254 (2011), eqn. (14) *)
628 mathematica comment (* removing trA from Aij ensures that detg = 1 *)
629 mathematica code dot[gt[la,lb]] -> - 2 alpha (At[la,lb] - IfCCZ4[(1/3) At[lc,ld] gtu[uc,ud] gt[la,lb], 0])
630 mathematica code + gt[la,lc] PD[beta[uc],lb] + gt[lb,lc] PD[beta[uc],la]
631 mathematica code - (2/3) gt[la,lb] PD[beta[uc],lc],
632 mathematica comment (* PRD 62, 044034 (2000), eqn. (20) *)
633 mathematica comment (* PRD 67 084023 (2003), eqn (26) *)
634 mathematica comment (* gr-qc:1106.2254 (2011), eqn. (19) *)
635 mathematica comment (* Adding Z terms by changing Xtn to Xt,
636 mathematica comment also adding extra Z and Theta terms *)
637 mathematica code dotXt[ui] -> - 2 Atu[ui,uj] PD[alpha,lj]
638 mathematica code + 2 alpha (+ Gt[ui,lj,lk] Atu[uk,uj]
639 mathematica code - (2/3) gtu[ui,uj] PD[trK,lj]
640 mathematica code + 6 Atu[ui,uj] cdphi[lj])
641 mathematica code + gtu[uj,ul] PD[beta[ui],lj,ll]
642 mathematica code + (1/3) gtu[ui,uj] PD[beta[ul],lj,ll]
643 mathematica code - Xtn[uj] PD[beta[ui],lj]
644 mathematica code + (2/3) Xtn[ui] PD[beta[uj],lj]
645 mathematica code + IfCCZ4[
646 mathematica code + GammaShift 2 e4phi (- Z[uj] PD[beta[ui],lj]
647 mathematica code + (2/3) Z[ui] PD[beta[uj],lj])
648 mathematica code - (4/3) alpha e4phi Z[ui] trK
649 mathematica code + 2 gtu[ui,uj] (+ alpha PD[Theta,lj]
650 mathematica code - Theta PD[alpha,lj])
651 mathematica code - 2 alpha e4phi dampk1 Z[ui],
652 mathematica code 0]
653 mathematica comment (* Equation (4.28) in Baumgarte & Shapiro (Phys. Rept. 376 (2003) 41-131) *)
654 mathematica code + addMatter (- 16 Pi alpha gtu[ui,uj] S[lj]),
655 mathematica code dot[Xt[ui]] -> dotXt[ui],
656 mathematica blank
657 mathematica comment (* gr-qc:1106.2254 (2011), eqn. (18) *)
658 mathematica code IfCCZ4[
659 mathematica code dotTheta ->
660 mathematica code - PD[alpha,la] Z[ua] - dampk1 (2 + dampk2) alpha Theta
661 mathematica code + (1/2) alpha (gu[ua,ub] R[la,lb] - Atm[ua,lb] Atm[ub,la] + (2/3) trK^2 - 2 trK Theta)
662 mathematica code + addMatter (- 8 Pi alpha rho)
663 mathematica code ],
664 mathematica blank
665 mathematica code IfCCZ4[
666 mathematica code dot[Theta] -> dotTheta
667 mathematica code ],
668 mathematica blank
669 mathematica comment (* PRD 62, 044034 (2000), eqn. (11) *)
670 mathematica comment (* gr-qc:1106.2254 (2011), eqn. (17) *)
671 mathematica comment (* Adding the RHS of Theta to K, because K_Z4 = K_BSSN + 2 Theta *)
672 mathematica comment (* Also adding the Z term, as it has to cancel with the one in Theta *)
673 mathematica code dottrK -> - em4phi ( gtu[ua,ub] ( PD[alpha,la,lb]
674 mathematica code + 2 cdphi[la] PD[alpha,lb] )
675 mathematica code - Xtn[ua] PD[alpha,la] )
676 mathematica code + alpha (Atm[ua,lb] Atm[ub,la] + (1/3) trK^2)
677 mathematica code + IfCCZ4[
678 mathematica code + 2 dotTheta + 2 PD[alpha,la] Z[ua]
679 mathematica code + dampk1 (1 - dampk2) alpha Theta,
680 mathematica code 0]
681 mathematica comment (* Equation (4.21) in Baumgarte & Shapiro (Phys. Rept. 376 (2003) 41-131) *)
682 mathematica code + addMatter (4 Pi alpha (rho + trS)),
683 mathematica code dot[trK] -> dottrK,
684 mathematica blank
685 mathematica comment (* PRD 62, 044034 (2000), eqn. (12) *)
686 mathematica comment (* TODO: Should we use the Hamiltonian constraint to make Rij tracefree? *)
687 mathematica comment (* gr-qc:1106.2254 (2011), eqn. (15) *)
688 mathematica comment (* Adding Z terms in the Ricci and Theta terms *)
689 mathematica code Ats[la,lb] -> - CDt[alpha,la,lb] +
690 mathematica code + 2 (PD[alpha,la] cdphi[lb] + PD[alpha,lb] cdphi[la] )
691 mathematica code + alpha R[la,lb],
692 mathematica code trAts -> gu[ua,ub] Ats[la,lb],
693 mathematica code dot[At[la,lb]] -> + em4phi (+ Ats[la,lb] - (1/3) g[la,lb] trAts )
694 mathematica code + alpha (+ ((trK - IfCCZ4[2 Theta, 0])
695 mathematica code At[la,lb])
696 mathematica code - 2 At[la,lc] Atm[uc,lb])
697 mathematica code + At[la,lc] PD[beta[uc],lb] + At[lb,lc] PD[beta[uc],la]
698 mathematica code - (2/3) At[la,lb] PD[beta[uc],lc]
699 mathematica comment (* Equation (4.23) in Baumgarte & Shapiro (Phys. Rept. 376 (2003) 41-131) *)
700 mathematica code + addMatter (- em4phi alpha 8 Pi
701 mathematica code (T[la,lb] - (1/3) g[la,lb] trS)),
702 mathematica blank
703 mathematica comment (* dot[alpha] -> - harmonicF alpha^harmonicN trK, *)
704 mathematica comment (* dot[alpha] -> - harmonicF alpha^harmonicN A + Lie[alpha, beta], *)
705 mathematica comment (*
706 mathematica comment dot[alpha] -> - harmonicF alpha^harmonicN (
707 mathematica comment (1 - LapseAdvectionCoeff) A + LapseAdvectionCoeff trK)
708 mathematica comment + LapseAdvectionCoeff beta[ua] PDu[alpha,la],
709 mathematica comment dot[A] -> (1 - LapseAdvectionCoeff) (dottrK - AlphaDriver A),
710 mathematica comment *)
711 mathematica code dot[alpha] -> - harmonicF alpha^harmonicN
712 mathematica code (+ LapseACoeff A
713 mathematica code + ((1 - LapseACoeff)
714 mathematica code (+ trK - IfCCZ4[2 Theta, 0]
715 mathematica code + AlphaDriver (alpha - 1)))),
716 mathematica blank
717 mathematica code dot[A] -> + (LapseACoeff
718 mathematica code (+ dottrK - IfCCZ4[2 dotTheta, 0]
719 mathematica code - AlphaDriver A)),
720 mathematica blank
721 mathematica code eta -> etaExpr,
722 mathematica code theta -> thetaExpr,
723 mathematica blank
724 mathematica comment (* dot[beta[ua]] -> eta Xt[ua], *)
725 mathematica comment (* dot[beta[ua]] -> ShiftGammaCoeff alpha^ShiftAlphaPower B[ua], *)
726 mathematica code dot[beta[ua]] -> IfThen[harmonicShift,
727 mathematica code - 1/2 gtu[ua,uj] phi alpha
728 mathematica code (- 2 alpha PD[phi,lj]
729 mathematica code + 2 phi PD[alpha,lj]
730 mathematica code + gtu[uk,ul] phi alpha
731 mathematica code (PD[gt[lk,ll],lj] - 2 PD[gt[lj,lk],ll])),
732 mathematica comment (* else *)
733 mathematica code + theta ShiftGammaCoeff
734 mathematica code (+ ShiftBCoeff B[ua]
735 mathematica code + (1 - ShiftBCoeff)
736 mathematica code (Xt[ua] - eta BetaDriver beta[ua]))],
737 mathematica blank
738 mathematica code dot[B[ua]] -> + ShiftBCoeff (dotXt[ua] - eta BetaDriver B[ua])
739 mathematica comment (* Note that this dotXt[ua] is not yet \partial_t \tilde \Gamma^i, because the
740 mathematica comment advection term has not yet been added. It is actually
741 mathematica comment \partial_t \tilde \Gamma^i - \beta^j \partial_j \tilde \Gamma^i *)
742 mathematica code }
743 mathematica code };
744 mathematica blank
745 mathematica code advectCalc =
746 mathematica code {
747 mathematica code Name -> thorn <> "_Advect",
748 mathematica code Schedule -> {"IN " <> thorn <> "_evolCalcGroup " <>
749 mathematica code "AFTER (" <> thorn <> "_RHS " <> thorn <> "_RHS1 " <> thorn <> "_RHS2)"},
750 mathematica comment (*
751 mathematica comment Where -> Interior,
752 mathematica comment *)
753 mathematica comment (* Synchronise the RHS grid functions after this routine, so that
754 mathematica comment the refinement boundaries are set correctly before applying the
755 mathematica comment radiative boundary conditions. *)
756 mathematica code Where -> InteriorNoSync,
757 mathematica code ConditionalOnKeyword -> {"advection_split", "combined"},
758 mathematica code Shorthands -> {dir[ua]},
759 mathematica code Equations ->
760 mathematica code {
761 mathematica code dir[ua] -> Sign[beta[ua]],
762 mathematica blank
763 mathematica code dot[phi] -> dot[phi] + Upwind[beta[ua], phi, la],
764 mathematica blank
765 mathematica code dot[gt[la,lb]] -> dot[gt[la,lb]] + Upwind[beta[uc], gt[la,lb], lc],
766 mathematica blank
767 mathematica code dot[Xt[ui]] -> dot[Xt[ui]] + Upwind[beta[uj], Xt[ui], lj],
768 mathematica blank
769 mathematica code IfCCZ4[
770 mathematica code dot[Theta] -> dot[Theta] + Upwind[beta[ua], Theta, la]
771 mathematica code ],
772 mathematica blank
773 mathematica code dot[trK] -> dot[trK] + Upwind[beta[ua], trK, la],
774 mathematica blank
775 mathematica code dot[At[la,lb]] -> dot[At[la,lb]] + Upwind[beta[uc], At[la,lb], lc],
776 mathematica blank
777 mathematica code dot[alpha] -> dot[alpha]
778 mathematica code + LapseAdvectionCoeff Upwind[beta[ua], alpha, la],
779 mathematica blank
780 mathematica code dot[A] -> dot[A]
781 mathematica code + LapseACoeff (
782 mathematica code + LapseAdvectionCoeff Upwind[beta[ua], A, la]
783 mathematica code + (1 - LapseAdvectionCoeff) Upwind[beta[ua], trK, la]),
784 mathematica blank
785 mathematica code dot[beta[ua]] -> dot[beta[ua]]
786 mathematica code + ShiftAdvectionCoeff Upwind[beta[ub], beta[ua], lb],
787 mathematica blank
788 mathematica code dot[B[ua]] -> dot[B[ua]]
789 mathematica code + ShiftBCoeff (
790 mathematica code + ShiftAdvectionCoeff Upwind[beta[ub], B[ua], lb]
791 mathematica code + ((1 - ShiftAdvectionCoeff)
792 mathematica code Upwind[beta[ub], Xt[ua], lb]))
793 mathematica comment (* Note that the advection term \beta^j \partial_j \tilde \Gamma^i is not
794 mathematica comment subtracted here when ShiftAdvectionCoefficient == 1 because it was
795 mathematica comment implicitly subtracted before (see comment in previous calculation of
796 mathematica comment dot[B[ua]]. *)
797 mathematica code }
798 mathematica code };
799 mathematica blank
800 mathematica code varsNames = {
801 mathematica code {"phi", dot[phi]},
802 mathematica code {"gt", dot[gt[la,lb]]},
803 mathematica code {"Xt", dot[Xt[ui]]},
804 mathematica code {"trK", dot[trK]},
805 mathematica code {"At", dot[At[la,lb]]},
806 mathematica code {"alpha", dot[alpha]},
807 mathematica code {"A", dot[A]},
808 mathematica code {"beta", dot[beta[ua]]},
809 mathematica code {"B", dot[B[ua]]},
810 mathematica code IfCCZ4[{"Theta", dot[Theta]}]
811 mathematica code };
812 mathematica blank
813 mathematica code advectCalcs = Map[
814 mathematica code PartialCalculation[advectCalc, "_"<>ToString[First[#]],
815 mathematica code {ConditionalOnKeyword -> {"advection_split",
816 mathematica code "per variable"}},
817 mathematica code {Last[#]}]&,
818 mathematica code varsNames];
819 mathematica blank
820 mathematica code evolCalc1 = PartialCalculation[evolCalc, "1",
821 mathematica code {
822 mathematica code ConditionalOnKeyword -> {"RHS_split", "split At"}
823 mathematica code },
824 mathematica code {
825 mathematica code dot[phi],
826 mathematica code dot[gt[la,lb]],
827 mathematica code dot[Xt[ui]],
828 mathematica code dot[trK],
829 mathematica code dot[alpha],
830 mathematica code dot[A],
831 mathematica code dot[beta[ua]],
832 mathematica code dot[B[ua]],
833 mathematica code IfCCZ4[dot[Theta]]
834 mathematica code }];
835 mathematica blank
836 mathematica code evolCalc2 = PartialCalculation[evolCalc, "2",
837 mathematica code {
838 mathematica code ConditionalOnKeyword -> {"RHS_split", "split At"}
839 mathematica code },
840 mathematica code {
841 mathematica code dot[At[la,lb]]
842 mathematica code }];
843 mathematica blank
844 mathematica code dissCalc =
845 mathematica code {
846 mathematica code Name -> thorn <> "_Dissipation",
847 mathematica code Schedule -> {"IN " <> thorn <> "_evolCalcGroup " <>
848 mathematica code "AFTER (" <> thorn <> "_RHS1 " <> thorn <> "_RHS2)"},
849 mathematica code ConditionalOnKeyword -> {"apply_dissipation", "always"},
850 mathematica code Where -> InteriorNoSync,
851 mathematica code Shorthands -> {epsdiss[ua]},
852 mathematica code Equations ->
853 mathematica code {
854 mathematica code epsdiss[ua] -> EpsDiss,
855 mathematica code Sequence@@Table[
856 mathematica code dot[var] -> dot[var] + epsdiss[ux] PDdiss[var,lx],
857 mathematica code {var, {phi, gt[la,lb], Xt[ui], IfCCZ4[Theta], trK, At[la,lb],
858 mathematica code alpha, A, beta[ua], B[ua]}}]
859 mathematica code }
860 mathematica code };
861 mathematica blank
862 mathematica code dissCalcs =
863 mathematica code Table[
864 mathematica code {
865 mathematica code Name -> thorn <> "_Dissipation_" <> ToString[var /. {Tensor[n_,__] -> n}],
866 mathematica code Schedule -> {"IN " <> thorn <> "_evolCalcGroup " <>
867 mathematica code "AFTER (" <> thorn <> "_RHS1 " <> thorn <> "_RHS2)"},
868 mathematica code ConditionalOnKeyword -> {"apply_dissipation", "always"},
869 mathematica code Where -> InteriorNoSync,
870 mathematica code Shorthands -> {epsdiss[ua]},
871 mathematica code Equations ->
872 mathematica code {
873 mathematica code epsdiss[ua] -> EpsDiss,
874 mathematica code dot[var] -> dot[var] + epsdiss[ux] PDdiss[var,lx]
875 mathematica code }
876 mathematica code },
877 mathematica code {var, {phi, gt[la,lb], Xt[ui], IfCCZ4[Theta], trK, At[la,lb],
878 mathematica code alpha, A, beta[ua], B[ua]}}
879 mathematica code ];
880 mathematica blank
881 mathematica code RHSStaticBoundaryCalc =
882 mathematica code {
883 mathematica code Name -> thorn <> "_RHSStaticBoundary",
884 mathematica code Schedule -> {"IN MoL_CalcRHS"},
885 mathematica code ConditionalOnKeyword -> {"my_rhs_boundary_condition", "static"},
886 mathematica code Where -> Boundary,
887 mathematica code Equations ->
888 mathematica code {
889 mathematica code dot[phi] -> 0,
890 mathematica code dot[gt[la,lb]] -> 0,
891 mathematica code dot[trK] -> 0,
892 mathematica code dot[At[la,lb]] -> 0,
893 mathematica code dot[Xt[ua]] -> 0,
894 mathematica code dot[alpha] -> 0,
895 mathematica code dot[A] -> 0,
896 mathematica code dot[beta[ua]] -> 0,
897 mathematica code dot[B[ua]] -> 0,
898 mathematica code IfCCZ4[dot[Theta] -> 0]
899 mathematica code }
900 mathematica code };
901 mathematica blank
902 mathematica comment (* Initialise the RHS variables in analysis in case they are going to
903 mathematica comment be output - the noninterior points cannot be filled, so we define
904 mathematica comment them to be zero *)
905 mathematica code initRHSCalc =
906 mathematica code {
907 mathematica code Name -> thorn <> "_InitRHS",
908 mathematica code Schedule -> {"AT analysis BEFORE " <> thorn <> "_evolCalcGroup"},
909 mathematica code Where -> Everywhere,
910 mathematica code Equations ->
911 mathematica code {
912 mathematica code dot[phi] -> 0,
913 mathematica code dot[gt[la,lb]] -> 0,
914 mathematica code dot[trK] -> 0,
915 mathematica code dot[At[la,lb]] -> 0,
916 mathematica code dot[Xt[ua]] -> 0,
917 mathematica code dot[alpha] -> 0,
918 mathematica code dot[A] -> 0,
919 mathematica code dot[beta[ua]] -> 0,
920 mathematica code dot[B[ua]] -> 0,
921 mathematica code IfCCZ4[dot[Theta] -> 0]
922 mathematica code }
923 mathematica code };
924 mathematica blank
925 mathematica code RHSRadiativeBoundaryCalc =
926 mathematica code {
927 mathematica code Name -> thorn <> "_RHSRadiativeBoundary",
928 mathematica code Schedule -> {"IN MoL_CalcRHS"},
929 mathematica code ConditionalOnKeyword -> {"my_rhs_boundary_condition", "radiative"},
930 mathematica code Where -> Boundary,
931 mathematica code Shorthands -> {dir[ua],
932 mathematica code detgt, gtu[ua,ub], em4phi, gu[ua,ub],
933 mathematica code nn[la], nu[ua], nlen, nlen2, su[ua],
934 mathematica code vg},
935 mathematica code Equations ->
936 mathematica code {
937 mathematica code dir[ua] -> Sign[normal[ua]],
938 mathematica blank
939 mathematica code detgt -> 1 (* detgtExpr *),
940 mathematica code gtu[ua,ub] -> 1/detgt detgtExpr MatrixInverse [gt[ua,ub]],
941 mathematica code em4phi -> IfThen[conformalMethod==CMW, phi^2, Exp[-4 phi]],
942 mathematica code gu[ua,ub] -> em4phi gtu[ua,ub],
943 mathematica blank
944 mathematica code nn[la] -> Euc[la,lb] normal[ub],
945 mathematica code nu[ua] -> gu[ua,ub] nn[lb],
946 mathematica code nlen2 -> nu[ua] nn[la],
947 mathematica code nlen -> Sqrt[nlen2],
948 mathematica code su[ua] -> nu[ua] / nlen,
949 mathematica blank
950 mathematica code vg -> Sqrt[harmonicF],
951 mathematica blank
952 mathematica code dot[phi] -> - vg su[uc] PDo[phi ,lc],
953 mathematica code dot[gt[la,lb]] -> - su[uc] PDo[gt[la,lb],lc],
954 mathematica code dot[trK] -> - vg su[uc] PDo[trK ,lc],
955 mathematica code dot[At[la,lb]] -> - su[uc] PDo[At[la,lb],lc],
956 mathematica code dot[Xt[ua]] -> - su[uc] PDo[Xt[ua] ,lc],
957 mathematica code dot[alpha] -> - vg su[uc] PDo[alpha ,lc],
958 mathematica code dot[A] -> - vg su[uc] PDo[A ,lc],
959 mathematica code dot[beta[ua]] -> - su[uc] PDo[beta[ua] ,lc],
960 mathematica code dot[B[ua]] -> - su[uc] PDo[B[ua] ,lc],
961 mathematica code IfCCZ4[
962 mathematica code dot[Theta] -> - vg su[uc] PDo[Theta ,lc]
963 mathematica code ]
964 mathematica code }
965 mathematica code };
966 mathematica blank
967 mathematica code enforceCalc =
968 mathematica code {
969 mathematica code Name -> thorn <> "_enforce",
970 mathematica code Schedule -> {"IN MoL_PostStepModify"},
971 mathematica code Shorthands -> {detgt, gtu[ua,ub], trAt},
972 mathematica code Equations ->
973 mathematica code {
974 mathematica comment (* The following comment is still interesting, but is not correct
975 mathematica comment any more since it is now scheduled in MoL_PostStepModify instead:
976 mathematica blank
977 mathematica comment Enforcing the constraints needs to be a projection, because it
978 mathematica comment is applied in MoL_PostStep and may thus be applied multiple
979 mathematica comment times, not only during time evolution. Therefore detgt has to
980 mathematica comment be calculated correctly, without assuming that det gt_ij = 1,
981 mathematica comment which is not always the case (since we don't enforce it). On
982 mathematica comment the other hand, this may not be so important... *)
983 mathematica code detgt -> 1 (* detgtExpr *),
984 mathematica code gtu[ua,ub] -> 1/detgt detgtExpr MatrixInverse [gt[ua,ub]],
985 mathematica blank
986 mathematica code trAt -> gtu[ua,ub] At[la,lb],
987 mathematica blank
988 mathematica code At[la,lb] -> At[la,lb] - (1/3) gt[la,lb] trAt,
989 mathematica blank
990 mathematica code alpha -> Max[alpha, MinimumLapse]
991 mathematica code }
992 mathematica code };
993 mathematica blank
994 mathematica comment (******************************************************************************)
995 mathematica comment (* Boundary conditions *)
996 mathematica comment (******************************************************************************)
997 mathematica blank
998 mathematica code boundaryCalc =
999 mathematica code {
1000 mathematica code Name -> thorn <> "_boundary",
1001 mathematica code Schedule -> {"IN MoL_PostStep"},
1002 mathematica code ConditionalOnKeyword -> {"my_boundary_condition", "Minkowski"},
1003 mathematica code Where -> BoundaryWithGhosts,
1004 mathematica code Equations ->
1005 mathematica code {
1006 mathematica code phi -> IfThen[conformalMethod==CMW, 1, 0],
1007 mathematica code gt[la,lb] -> KD[la,lb],
1008 mathematica code trK -> 0,
1009 mathematica code At[la,lb] -> 0,
1010 mathematica code Xt[ua] -> 0,
1011 mathematica code alpha -> 1,
1012 mathematica code A -> 0,
1013 mathematica code beta[ua] -> 0,
1014 mathematica code B[ua] -> 0,
1015 mathematica code IfCCZ4[Theta -> 0]
1016 mathematica code }
1017 mathematica code };
1018 mathematica blank
1019 mathematica comment (******************************************************************************)
1020 mathematica comment (* Constraint equations *)
1021 mathematica comment (******************************************************************************)
1022 mathematica blank
1023 mathematica code constraintsCalc =
1024 mathematica code {
1025 mathematica code Name -> thorn <> "_constraints",
1026 mathematica code Schedule -> Automatic,
1027 mathematica code After -> "MoL_PostStep",
1028 mathematica code Where -> Interior,
1029 mathematica code Shorthands -> {detgt, ddetgt[la], gtu[ua,ub], Z[ua],
1030 mathematica code Gt[ua,lb,lc], Gtl[la,lb,lc], Gtlu[la,lb,uc], Xtn[ua],
1031 mathematica code e4phi, em4phi,
1032 mathematica code g[la,lb], detg, gu[ua,ub], ddetg[la], G[ua,lb,lc],
1033 mathematica code Rt[la,lb], Rphi[la,lb], R[la,lb], trR, Atm[ua,lb],
1034 mathematica code gK[la,lb,lc], cdphi[la], cdphi2[la,lb],
1035 mathematica code rho, S[la], fac1, fac2},
1036 mathematica code Equations ->
1037 mathematica code {
1038 mathematica code detgt -> 1 (* detgtExpr *),
1039 mathematica code ddetgt[la] -> 0 (* ddetgtExpr[la] *),
1040 mathematica blank
1041 mathematica comment (* This leads to simpler code... *)
1042 mathematica code gtu[ua,ub] -> 1/detgt detgtExpr MatrixInverse [gt[ua,ub]],
1043 mathematica code Gtl[la,lb,lc] -> 1/2
1044 mathematica code (PD[gt[lb,la],lc] + PD[gt[lc,la],lb] - PD[gt[lb,lc],la]),
1045 mathematica code Gtlu[la,lb,uc] -> gtu[uc,ud] Gtl[la,lb,ld],
1046 mathematica code Gt[ua,lb,lc] -> gtu[ua,ud] Gtl[ld,lb,lc],
1047 mathematica blank
1048 mathematica comment (* The conformal connection functions calculated from the conformal metric,
1049 mathematica comment used instead of Xt where no derivatives of Xt are taken *)
1050 mathematica code Xtn[ui] -> gtu[uj,uk] Gt[ui,lj,lk],
1051 mathematica blank
1052 mathematica code e4phi -> IfThen[conformalMethod==CMW, 1/phi^2, Exp[4 phi]],
1053 mathematica code em4phi -> 1 / e4phi,
1054 mathematica code g[la,lb] -> e4phi gt[la,lb],
1055 mathematica code detg -> e4phi^3,
1056 mathematica code gu[ua,ub] -> em4phi gtu[ua,ub],
1057 mathematica blank
1058 mathematica comment (* The Z quantities *)
1059 mathematica code IfCCZ4[
1060 mathematica code Z[ud] -> (1/2) gu[ua,ud] (- PD[gt[la,lb],lc] gtu[ub,uc] + gt[la,lc] Xt[uc])
1061 mathematica code ],
1062 mathematica blank
1063 mathematica comment (* PRD 62, 044034 (2000), eqn. (18) *)
1064 mathematica code Rt[li,lj] -> - (1/2) gtu[ul,um] PD[gt[li,lj],ll,lm]
1065 mathematica code + (1/2) gt[lk,li] PD[Xt[uk],lj]
1066 mathematica code + (1/2) gt[lk,lj] PD[Xt[uk],li]
1067 mathematica code + (1/2) Xtn[uk] Gtl[li,lj,lk]
1068 mathematica code + (1/2) Xtn[uk] Gtl[lj,li,lk]
1069 mathematica code + (+ Gt[uk,li,ll] Gtlu[lj,lk,ul]
1070 mathematica code + Gt[uk,lj,ll] Gtlu[li,lk,ul]
1071 mathematica code + Gt[uk,li,ll] Gtlu[lk,lj,ul]),
1072 mathematica blank
1073 mathematica comment (* From the long turducken paper.
1074 mathematica comment This expression seems to give the same result as the one from 044034. *)
1075 mathematica comment (* TODO: symmetrise correctly: (ij) = (1/2) [i+j] *)
1076 mathematica comment (*
1077 mathematica comment Rt[li,lj] -> - (1/2) gtu[uk,ul] PD[gt[li,lj],lk,ll]
1078 mathematica comment + gt[lk,li] PD[Xt[uk],lj] + gt[lk,lj] PD[Xt[uk],li]
1079 mathematica comment + gt[li,ln] Gt[un,lj,lk] gtu[um,ua] gtu[uk,ub] PD[gt[la,lb],lm]
1080 mathematica comment + gt[lj,ln] Gt[un,li,lk] gtu[um,ua] gtu[uk,ub] PD[gt[la,lb],lm]
1081 mathematica comment + gtu[ul,us] (+ 2 Gt[uk,ll,li] gt[lj,ln] Gt[un,lk,ls]
1082 mathematica comment + 2 Gt[uk,ll,lj] gt[li,ln] Gt[un,lk,ls]
1083 mathematica comment + Gt[uk,li,ls] gt[lk,ln] Gt[un,ll,lj]),
1084 mathematica comment *)
1085 mathematica blank
1086 mathematica comment (* Below would be a straightforward calculation,
1087 mathematica comment without taking any Gamma^i into account.
1088 mathematica comment This expression gives a different answer! *)
1089 mathematica comment (*
1090 mathematica comment Rt[la,lb] -> + Gt[u1,l2,la] Gt[l1,lb,u2] - Gt[u1,la,lb] Gt[l1,l2,u2]
1091 mathematica comment + 1/2 gtu[u1,u2] (- PD[gt[l1,l2],la,lb] + PD[gt[l1,la],l2,lb]
1092 mathematica comment - PD[gt[la,lb],l1,l2] + PD[gt[l2,lb],l1,la]),
1093 mathematica comment *)
1094 mathematica blank
1095 mathematica code fac1 -> IfThen[conformalMethod==CMW, -1/(2 phi), 1],
1096 mathematica code cdphi[la] -> fac1 CDt[phi,la],
1097 mathematica code fac2 -> IfThen[conformalMethod==CMW, 1/(2 phi^2), 0],
1098 mathematica code cdphi2[la,lb] -> fac1 CDt[phi,la,lb] + fac2 CDt[phi,la] CDt[phi,lb],
1099 mathematica blank
1100 mathematica comment (* PRD 62, 044034 (2000), eqn. (15) *)
1101 mathematica code Rphi[li,lj] -> - 2 cdphi2[lj,li]
1102 mathematica code - 2 gt[li,lj] gtu[ul,un] cdphi2[ll,ln]
1103 mathematica code + 4 cdphi[li] cdphi[lj]
1104 mathematica code - 4 gt[li,lj] gtu[ul,un] cdphi[ln] cdphi[ll],
1105 mathematica blank
1106 mathematica comment (* ddetg[la] -> PD[e4phi detg,la], *)
1107 mathematica code ddetg[la] -> e4phi ddetgt[la] + 4 detgt e4phi PD[phi,la],
1108 mathematica comment (* TODO: check this equation, maybe simplify it by omitting ddetg *)
1109 mathematica code G[ua,lb,lc] -> Gt[ua,lb,lc]
1110 mathematica code + 1/(2 detg) (+ KD[ua,lb] ddetg[lc] + KD[ua,lc] ddetg[lb]
1111 mathematica code - (1/3) g[lb,lc] gu[ua,ud] ddetg[ld]),
1112 mathematica blank
1113 mathematica code R[la,lb] -> + Rt[la,lb] + Rphi[la,lb],
1114 mathematica blank
1115 mathematica code IfCCZ4[
1116 mathematica code R[la,lb] -> R[la, lb] + (2/phi) (+ g[la,lc] Z[uc] PD[phi,lb]
1117 mathematica code + g[lb,lc] Z[uc] PD[phi,la] - g[la,lb] Z[uc] PD[phi,lc])
1118 mathematica code + e4phi Z[uc] PD[gt[la,lb],lc]
1119 mathematica code ],
1120 mathematica blank
1121 mathematica code trR -> gu[ua,ub] R[la,lb],
1122 mathematica blank
1123 mathematica comment (* K[la,lb] -> e4phi At[la,lb] + (1/3) g[la,lb] trK, *)
1124 mathematica comment (* Km[ua,lb] -> gu[ua,uc] K[lc,lb], *)
1125 mathematica code Atm[ua,lb] -> gtu[ua,uc] At[lc,lb],
1126 mathematica blank
1127 mathematica comment (* Matter terms *)
1128 mathematica blank
1129 mathematica comment (* rho = n^a n^b T_ab *)
1130 mathematica code rho -> 1/alpha^2 (T00 - 2 beta[ui] T0[li] + beta[ui] beta[uj] T[li,lj]),
1131 mathematica blank
1132 mathematica comment (* S_i = -p^a_i n^b T_ab, where p^a_i = delta^a_i + n^a n_i *)
1133 mathematica code S[li] -> -1/alpha (T0[li] - beta[uj] T[li,lj]),
1134 mathematica blank
1135 mathematica comment (* Constraints *)
1136 mathematica blank
1137 mathematica comment (* H -> trR - Km[ua,lb] Km[ub,la] + trK^2, *)
1138 mathematica comment (* PRD 67, 084023 (2003), eqn. (19) *)
1139 mathematica code H -> trR - Atm[ua,lb] Atm[ub,la] + (2/3) trK^2 - addMatter 16 Pi rho,
1140 mathematica blank
1141 mathematica comment (* gK[la,lb,lc] -> CD[K[la,lb],lc], *)
1142 mathematica comment (* gK[la,lb,lc] -> + 4 e4phi PD[phi,lc] At[la,lb] + e4phi CD[At[la,lb],lc]
1143 mathematica comment + (1/3) g[la,lb] PD[trK,lc],
1144 mathematica comment M[la] -> gu[ub,uc] (gK[lc,la,lb] - gK[lc,lb,la]), *)
1145 mathematica blank
1146 mathematica code M[li] -> + gtu[uj,uk] (CDt[At[li,lj],lk] + 6 At[li,lj] cdphi[lk])
1147 mathematica code - (2/3) PD[trK,li]
1148 mathematica code - addMatter 8 Pi S[li],
1149 mathematica comment (* TODO: use PRD 67, 084023 (2003), eqn. (20) *)
1150 mathematica blank
1151 mathematica comment (* det gamma-tilde *)
1152 mathematica code cS -> Log[detgt],
1153 mathematica blank
1154 mathematica comment (* Gamma constraint *)
1155 mathematica code cXt[ua] -> gtu[ub,uc] Gt[ua,lb,lc] - Xt[ua],
1156 mathematica blank
1157 mathematica comment (* trace A-tilde *)
1158 mathematica code cA -> gtu[ua,ub] At[la,lb]
1159 mathematica code }
1160 mathematica code };
1161 mathematica blank
1162 mathematica code constraintsCalc1 = PartialCalculation[constraintsCalc, "1",
1163 mathematica code {},
1164 mathematica code {
1165 mathematica code H
1166 mathematica code }];
1167 mathematica blank
1168 mathematica code constraintsCalc2 = PartialCalculation[constraintsCalc, "2",
1169 mathematica code {},
1170 mathematica code {
1171 mathematica code M[li],
1172 mathematica code cS,
1173 mathematica code cXt[ua],
1174 mathematica code cA
1175 mathematica code }];
1176 mathematica blank
1177 mathematica comment (******************************************************************************)
1178 mathematica comment (* Implementations *)
1179 mathematica comment (******************************************************************************)
1180 mathematica blank
1181 mathematica code inheritedImplementations =
1182 mathematica code Join[{"ADMBase"},
1183 mathematica code If [addMatter!=0, {"TmunuBase"}, {}]];
1184 mathematica blank
1185 mathematica comment (******************************************************************************)
1186 mathematica comment (* Parameters *)
1187 mathematica comment (******************************************************************************)
1188 mathematica blank
1189 mathematica code inheritedKeywordParameters = {};
1190 mathematica blank
1191 mathematica code extendedKeywordParameters =
1192 mathematica code {
1193 mathematica code {
1194 mathematica code Name -> "ADMBase::evolution_method",
1195 mathematica code AllowedValues -> {thorn}
1196 mathematica code },
1197 mathematica code {
1198 mathematica code Name -> "ADMBase::lapse_evolution_method",
1199 mathematica code AllowedValues -> {thorn}
1200 mathematica code },
1201 mathematica code {
1202 mathematica code Name -> "ADMBase::shift_evolution_method",
1203 mathematica code AllowedValues -> {thorn}
1204 mathematica code },
1205 mathematica code {
1206 mathematica code Name -> "ADMBase::dtlapse_evolution_method",
1207 mathematica code AllowedValues -> {thorn}
1208 mathematica code },
1209 mathematica code {
1210 mathematica code Name -> "ADMBase::dtshift_evolution_method",
1211 mathematica code AllowedValues -> {thorn}
1212 mathematica code }
1213 mathematica code };
1214 mathematica blank
1215 mathematica code keywordParameters =
1216 mathematica code {
1217 mathematica code {
1218 mathematica code Name -> "my_initial_data",
1219 mathematica comment (* Visibility -> "restricted", *)
1220 mathematica comment (* Description -> "ddd", *)
1221 mathematica code AllowedValues -> {"ADMBase", "Minkowski"},
1222 mathematica code Default -> "ADMBase"
1223 mathematica code },
1224 mathematica code {
1225 mathematica code Name -> "my_initial_boundary_condition",
1226 mathematica code Visibility -> "restricted",
1227 mathematica comment (* Description -> "ddd", *)
1228 mathematica code AllowedValues -> {"none"},
1229 mathematica code Default -> "none"
1230 mathematica code },
1231 mathematica code {
1232 mathematica code Name -> "my_rhs_boundary_condition",
1233 mathematica code Visibility -> "restricted",
1234 mathematica comment (* Description -> "ddd", *)
1235 mathematica code AllowedValues -> {"none", "static", "radiative"},
1236 mathematica code Default -> "none"
1237 mathematica code },
1238 mathematica code {
1239 mathematica code Name -> "my_boundary_condition",
1240 mathematica comment (* Visibility -> "restricted", *)
1241 mathematica comment (* Description -> "ddd", *)
1242 mathematica code AllowedValues -> {"none", "Minkowski"},
1243 mathematica code Default -> "none"
1244 mathematica code },
1245 mathematica code {
1246 mathematica code Name -> "calculate_ADMBase_variables_at",
1247 mathematica code Visibility -> "restricted",
1248 mathematica comment (* Description -> "ddd", *)
1249 mathematica code AllowedValues -> {"MoL_PostStep", "CCTK_EVOL", "CCTK_ANALYSIS"},
1250 mathematica code Default -> "MoL_PostStep"
1251 mathematica code },
1252 mathematica code {
1253 mathematica code Name -> "UseSpatialBetaDriver_UNUSED",
1254 mathematica code Visibility -> "restricted",
1255 mathematica comment (* Description -> "ddd", *)
1256 mathematica code AllowedValues -> {"no", "yes"},
1257 mathematica code Default -> "no"
1258 mathematica code },
1259 mathematica code {
1260 mathematica code Name -> "dt_lapse_shift_method",
1261 mathematica code Description -> "Treatment of ADMBase dtlapse and dtshift",
1262 mathematica code AllowedValues -> {"correct",
1263 mathematica code "noLapseShiftAdvection" (* omit lapse and shift advection terms (faster) *)
1264 mathematica code },
1265 mathematica code Default -> "correct"
1266 mathematica code },
1267 mathematica code {
1268 mathematica code Name -> "apply_dissipation",
1269 mathematica code Description -> "Whether to apply dissipation to the RHSs",
1270 mathematica code AllowedValues -> {"always",
1271 mathematica code "never" (* yes and no keyword values confuse Cactus, and Kranc
1272 mathematica comment doesn't support boolean parameters *)
1273 mathematica code },
1274 mathematica code Default -> "never"
1275 mathematica code },
1276 mathematica code {
1277 mathematica code Name -> "RHS_split",
1278 mathematica code Description -> "How to split RHS calculation",
1279 mathematica code AllowedValues -> {"combined",
1280 mathematica code "split At"},
1281 mathematica code Default -> "split At"
1282 mathematica code },
1283 mathematica code {
1284 mathematica code Name -> "advection_split",
1285 mathematica code Description -> "How to split advection calculation",
1286 mathematica code AllowedValues -> {"combined",
1287 mathematica code "per variable"},
1288 mathematica code Default -> "combined"
1289 mathematica code }
1290 mathematica code };
1291 mathematica blank
1292 mathematica code intParameters =
1293 mathematica code {
1294 mathematica code {
1295 mathematica code Name -> harmonicN,
1296 mathematica code Description -> "d/dt alpha = - f alpha^n K (harmonic=2, 1+log=1)",
1297 mathematica code Default -> 2
1298 mathematica code },
1299 mathematica code {
1300 mathematica code Name -> ShiftAlphaPower,
1301 mathematica code Default -> 0
1302 mathematica code },
1303 mathematica code {
1304 mathematica code Name -> conformalMethod,
1305 mathematica code Description -> "Treatment of conformal factor",
1306 mathematica code AllowedValues -> {{Value -> "0", Description -> "phi method"},
1307 mathematica code {Value -> "1", Description -> "W method"}},
1308 mathematica code Default -> 0
1309 mathematica code },
1310 mathematica code {
1311 mathematica code Name -> fdOrder,
1312 mathematica code Default -> derivOrder,
1313 mathematica code AllowedValues -> {2,4,6,8}
1314 mathematica code },
1315 mathematica code {
1316 mathematica code Name -> harmonicShift,
1317 mathematica code Description -> "Whether to use the harmonic shift",
1318 mathematica code AllowedValues -> {{Value -> "0", Description -> "Gamma driver shift"},
1319 mathematica code {Value -> "1", Description -> "Harmonic shift"}},
1320 mathematica code Default -> 0
1321 mathematica code }
1322 mathematica code };
1323 mathematica blank
1324 mathematica code realParameters =
1325 mathematica code {
1326 mathematica code IfCCZ4[{
1327 mathematica code Name -> GammaShift,
1328 mathematica code Description -> "Covariant shift term in Gamma",
1329 mathematica code Default -> 0.5
1330 mathematica code }],
1331 mathematica code IfCCZ4[{
1332 mathematica code Name -> dampk1,
1333 mathematica code Description -> "CCZ4 damping term 1 for Theta and Z",
1334 mathematica code Default -> 0
1335 mathematica code }],
1336 mathematica code IfCCZ4[{
1337 mathematica code Name -> dampk2,
1338 mathematica code Description -> "CCZ4 damping term 2 for Theta and Z",
1339 mathematica code Default -> 0
1340 mathematica code }],
1341 mathematica code {
1342 mathematica code Name -> LapseACoeff,
1343 mathematica code Description -> "Whether to evolve A in time",
1344 mathematica code Default -> 0
1345 mathematica code },
1346 mathematica code {
1347 mathematica code Name -> harmonicF,
1348 mathematica code Description -> "d/dt alpha = - f alpha^n K (harmonic=1, 1+log=2)",
1349 mathematica code Default -> 1
1350 mathematica code },
1351 mathematica code {
1352 mathematica code Name -> AlphaDriver,
1353 mathematica code Default -> 0
1354 mathematica code },
1355 mathematica code {
1356 mathematica code Name -> ShiftBCoeff,
1357 mathematica code Description -> "Whether to evolve B^i in time",
1358 mathematica code Default -> 1
1359 mathematica code },
1360 mathematica code {
1361 mathematica code Name -> ShiftGammaCoeff,
1362 mathematica code Default -> 0
1363 mathematica code },
1364 mathematica code {
1365 mathematica code Name -> BetaDriver,
1366 mathematica code Default -> 0
1367 mathematica code },
1368 mathematica code {
1369 mathematica code Name -> LapseAdvectionCoeff,
1370 mathematica code Description -> "Factor in front of the lapse advection terms in 1+log",
1371 mathematica code Default -> 1
1372 mathematica code },
1373 mathematica code {
1374 mathematica code Name -> ShiftAdvectionCoeff,
1375 mathematica code Description -> "Factor in front of the shift advection terms in gamma driver",
1376 mathematica code Default -> 1
1377 mathematica code },
1378 mathematica code {
1379 mathematica code Name -> MinimumLapse,
1380 mathematica code Description -> "Minimum value of the lapse function",
1381 mathematica code Default -> -1
1382 mathematica code },
1383 mathematica code {
1384 mathematica code Name -> SpatialBetaDriverRadius,
1385 mathematica code Description -> "Radius at which the BetaDriver starts to be reduced",
1386 mathematica code AllowedValues -> {{Value -> "(0:*", Description -> "Positive"}},
1387 mathematica code Default -> 10^12
1388 mathematica code },
1389 mathematica code {
1390 mathematica code Name -> SpatialShiftGammaCoeffRadius,
1391 mathematica code Description -> "Radius at which the ShiftGammaCoefficient starts to be reduced",
1392 mathematica code AllowedValues -> {{Value -> "(0:*", Description -> "Positive"}},
1393 mathematica code Default -> 10^12
1394 mathematica code },
1395 mathematica code {
1396 mathematica code Name -> EpsDiss,
1397 mathematica code Description -> "Dissipation strength",
1398 mathematica code AllowedValues -> {{Value -> "(0:*", Description -> "Positive"}},
1399 mathematica code Default -> 0
1400 mathematica code }
1401 mathematica code };
1402 mathematica blank
1403 mathematica comment (******************************************************************************)
1404 mathematica comment (* Construct the thorns *)
1405 mathematica comment (******************************************************************************)
1406 mathematica blank
1407 mathematica code calculations =
1408 mathematica code Join[
1409 mathematica code {
1410 mathematica code initialCalc,
1411 mathematica code convertFromADMBaseCalc,
1412 mathematica code initGammaCalc,
1413 mathematica code convertFromADMBaseGammaCalc,
1414 mathematica code evolCalc,
1415 mathematica code evolCalc1, evolCalc2,
1416 mathematica code dissCalc,
1417 mathematica code advectCalc,
1418 mathematica comment (*advectCalcs,*)
1419 mathematica code initRHSCalc,
1420 mathematica code RHSStaticBoundaryCalc,
1421 mathematica comment (* RHSRadiativeBoundaryCalc, *)
1422 mathematica code enforceCalc,
1423 mathematica code boundaryCalc,
1424 mathematica code convertToADMBaseCalc,
1425 mathematica code convertToADMBaseDtLapseShiftCalc,
1426 mathematica code convertToADMBaseDtLapseShiftBoundaryCalc,
1427 mathematica code convertToADMBaseFakeDtLapseShiftCalc,
1428 mathematica comment (* constraintsCalc, *)
1429 mathematica code constraintsCalc1, constraintsCalc2
1430 mathematica code },
1431 mathematica code advectCalcs
1432 mathematica comment (*dissCalcs*)
1433 mathematica code ];
1434 mathematica blank
1435 mathematica code CreateKrancThornTT [groups, ".", thorn,
1436 mathematica code Calculations -> calculations,
1437 mathematica code DeclaredGroups -> declaredGroupNames,
1438 mathematica code PartialDerivatives -> derivatives,
1439 mathematica code EvolutionTimelevels -> evolutionTimelevels,
1440 mathematica code DefaultEvolutionTimelevels -> 3,
1441 mathematica code UseJacobian -> True,
1442 mathematica code UseLoopControl -> True,
1443 mathematica code UseVectors -> useVectors,
1444 mathematica code UseOpenCL -> useOpenCL,
1445 mathematica code InheritedImplementations -> inheritedImplementations,
1446 mathematica code InheritedKeywordParameters -> inheritedKeywordParameters,
1447 mathematica code ExtendedKeywordParameters -> extendedKeywordParameters,
1448 mathematica code KeywordParameters -> keywordParameters,
1449 mathematica code IntParameters -> intParameters,
1450 mathematica code RealParameters -> realParameters
1451 mathematica code ];
1452 mathematica blank
1453 mathematica code ];
1454 mathematica blank
1455 mathematica blank
1456 mathematica blank
1457 mathematica comment (******************************************************************************)
1458 mathematica comment (* Options *)
1459 mathematica comment (******************************************************************************)
1460 mathematica blank
1461 mathematica comment (* These are the arguments to createComment:
1462 mathematica comment - derivative order: 2, 4, 6, 8, ...
1463 mathematica comment - useJacobian: False or True
1464 mathematica comment - split upwind derivatives: False or True
1465 mathematica comment - use vectorisation: False or True
1466 mathematica comment - use OpenCL: False or True
1467 mathematica comment - timelevels: 2 or 3
1468 mathematica comment ## (keep this at 3; this is better chosen with a run-time parameter)
1469 mathematica comment - matter: 0 or 1
1470 mathematica comment ## (matter seems cheap; it should be always enabled)
1471 mathematica comment - thorn base name
1472 mathematica comment *)
1473 mathematica blank
1474 mathematica code createCode[4, False, True, True , False, 3, 1, "BSSN"];
1475 mathematica code createCode[4, False, True, False, False, 3, 1, "BSSN"];
1476 mathematica code createCode[4, False, True, True , True , 3, 1, "BSSN"];
1477 mathematica blank
1478 mathematica code createCode[4, False, True, True , False, 3, 1, "CCZ4"];
1479 mathematica blank
33 octave comment ## 3-clause BSD license appended to this file.
44 octave blank
55 octave code function varargout = toledolu(LU)
6 octave comment ## -*- texinfo -*-
6 octave comment ## (*- texinfo -*)
77 octave comment ## @deftypefn{Function File} {[@var{L}, @var{U}, @var{P}]} = toledolu(@var{A})
88 octave comment ## @deftypefnx{Function File} {[@var{L}, @var{U}]} = toledolu(@var{A})
99 octave comment ## @deftypefnx{Function File} {@var{LUP}} = toledolu(@var{A})
1919 octave comment ## See the help for lu for details about the other calling forms.
2020 octave comment ##
2121 octave comment ## For the algorithm, see
22 octave comment ## @itemize
23 octave comment ## @item
22 octave comment ## (* @itemize *)
23 octave comment ## (* @item *)
2424 octave comment ## Toledo, Sivan. "Locality of reference in LU decomposition with
2525 octave comment ## partial pivoting," SIAM J. of Matrix Analysis and Applications,
2626 octave comment ## v18, n4, 1997. DOI: 10.1137/S0895479896297744
109109 pascal code end;
110110 pascal blank
111111 pascal code end.
112 pascal blank
113 pascal code class function Test.Run: Boolean;
114 pascal blank
115 pascal code #include <test.rh>
0 prolog comment /* test file for Prolog parsing */
1 prolog blank
2 prolog comment % this is a Prolog source file
3 prolog blank
4 prolog comment % select(Element, List, Remaining)
5 prolog blank
6 prolog code select(H, [H| T], T).
7 prolog code select(H, [X| R], [X| T]) :-
8 prolog code select(H, R, T).
0 puppet code class bob::open_ldap {
1 puppet blank
2 puppet code define foo::server (
3 puppet code $argsfile = undef,
4 puppet code $bdb_cachesize = '',
5 puppet code $bdb_checkpoint = '',
6 puppet code $bdb_directory = undef,
7 puppet code $bdb_idlcachesize = '',
8 puppet code $bdb_rootdn,
9 puppet code $bdb_rootpw,
10 puppet code $bdb_shm_key = '',
11 puppet code $bdb_suffix,
12 puppet code $conf_path = undef,
13 puppet code $conf_dir = undef,
14 puppet code $enable = false,
15 puppet code $include = [],
16 puppet code $includepath = undef,
17 puppet code $modulepath = '',
18 puppet code $modules = [],
19 puppet code $package = undef,
20 puppet code $pidfile = undef,
21 puppet code $sysconf_path = undef
22 puppet code ) {
23 puppet blank
24 puppet code $resource_name = "bob_openldap_server"
25 puppet blank
26 puppet code if($name != "params") {
27 puppet code fail("${resource_name}: This function is a singleton. Make sure the resource name is 'params'.")
28 puppet code }
29 puppet blank
30 puppet code case $operatingsystem {
31 puppet code Fedora: {
32 puppet code case $operatingsystemrelease {
33 puppet code /^(12|13)$/: {
34 puppet code if(!$argsfile) { $_argsfile = "/var/run/openldap/slapd.args" }
35 puppet code if(!$bdb_directory) { $_bdb_directory = "/var/lib/ldap" }
36 puppet code if(!$conf_path) { $_conf_path = "/etc/openldap/slapd.conf" }
37 puppet code if(!$conf_dir) { $_conf_dir = "/etc/openldap/slapd.d" }
38 puppet code if(!$package) { $_package = ["openldap-servers"] }
39 puppet code if(!$pidfile) { $_pidfile = "/var/run/openldap/slapd.pid" }
40 puppet code if(!$service) { $_service = "slapd" }
41 puppet code if(!$sysconf_path) { $_sysconf_path = "/etc/sysconfig/ldap" }
42 puppet code }
43 puppet code }
44 puppet code }
45 puppet code }
46 puppet blank
47 puppet comment # Presume the OS did not match and because these args are necessary, just
48 puppet comment # bail with an error.
49 puppet code if(!($_argsfile and $_bdb_directory and $_pidfile and $_conf_path and
50 puppet code $_package and $_service and $_sysconf_path and $_conf_dir)) {
51 puppet code fail("${resource_name}: Unsupported operating system: ${operatingsystem} version ${operatingsystemrelease} and you have not setup the args for: argsfile, bdb_directory, conf_dir, conf_path, package, pidfile, sysconf_path and service.")
52 puppet code }
53 puppet blank
54 puppet comment # Fix paths - add forward slashes at the end of strings without them
55 puppet code $_includepath = regsubst($includepath, '([^/])$', '\1/')
56 puppet code $_dbconf_path = "${_bdb_directory}/DB_CONFIG"
57 puppet blank
58 puppet comment # ...
59 puppet code file {
60 puppet code $_conf_path:
61 puppet code content => template("bob_openldap/slapd.conf"),
62 puppet code require => Package[$_package],
63 puppet code owner => "ldap",
64 puppet code group => "root",
65 puppet code mode => "0440",
66 puppet code notify => Service[$_service];
67 puppet code $_sysconf_path:
68 puppet code content => template("bob_openldap/ldap.sysconf"),
69 puppet code require => Package[$_package],
70 puppet code owner => "root",
71 puppet code group => "root",
72 puppet code mode => "0644";
73 puppet code $_conf_dir:
74 puppet code force => true,
75 puppet code ensure => absent,
76 puppet code before => Service[$_service];
77 puppet code $_dbconf_path:
78 puppet code content => "",
79 puppet code notify => Service[$_service];
80 puppet code }
81 puppet code package {
82 puppet code $_package:
83 puppet code ensure => installed;
84 puppet code }
85 puppet code service {
86 puppet code $_service:
87 puppet code ensure => $enable ? {
88 puppet code true => "running",
89 puppet code false => "stopped"
90 puppet code },
91 puppet code enable => $enable,
92 puppet code hasstatus => true,
93 puppet code require => [ Package[$_package], File[$_conf_path] ];
94 puppet code }
95 puppet code }
96 puppet blank
97 puppet code define client (
98 puppet code $base,
99 puppet code $network_timeout = '',
100 puppet code $path = undef,
101 puppet code $timeout = '',
102 puppet code $binddn = '',
103 puppet code $tls_cacertdir = undef,
104 puppet code $uri
105 puppet code ) {
106 puppet blank
107 puppet code $resource_name = "bob_openldap_client"
108 puppet blank
109 puppet code if($name != "params") {
110 puppet code fail("${resource_name}: This function is a singleton. Make sure the resource name is 'params'.")
111 puppet code }
112 puppet blank
113 puppet code case $operatingsystem {
114 puppet code Fedora: {
115 puppet code case $operatingsystemrelease {
116 puppet code /^(12|13)$/: {
117 puppet code if(!$tls_cacertdir) { $_tls_cacertdir = "/etc/openldap/cacerts" }
118 puppet code if(!$path) { $_path = "/etc/openldap/ldap.conf" }
119 puppet code }
120 puppet code }
121 puppet code }
122 puppet code }
123 puppet blank
124 puppet comment # Presume the OS did not match and because these args are necessary, just
125 puppet comment # bail with an error.
126 puppet code if(!($_tls_cacertdir and $_path)) {
127 puppet code fail("${resource_name}: Unsupported operating system: ${operatingsystem} version ${operatingsystemrelease} and you have not setup the args for: tls_cacertdir, path.")
128 puppet code }
129 puppet blank
130 puppet comment # Fix some vars, ready for templating
131 puppet code $_base = $base
132 puppet code $_binddn = $binddn
133 puppet code $_network_timeout = $network_timeout
134 puppet code $_timeout = $timeout
135 puppet code $_uri = $uri
136 puppet blank
137 puppet code file {
138 puppet code $_path:
139 puppet code content => template("bob_openldap/ldap.conf")
140 puppet code }
141 puppet blank
142 puppet code }
143 puppet blank
144 puppet code }
0 puppet code class tester (
1 puppet code ) {
2 puppet code "Some Content"
3 puppet code }
0 puppet code class test::files {
1 puppet code "Some Content"
2 puppet code }
0 puppet code include ::postfix
0 rebol comment ;; =================================================
1 rebol comment ;; Script: new-suffix.r
2 rebol comment ;; downloaded from: www.REBOL.org
3 rebol comment ;; on: 1-Jun-2011
4 rebol comment ;; at: 21:19:08.38986 UTC
5 rebol comment ;; owner: carl [script library member who can update
6 rebol comment ;; this script]
7 rebol comment ;; =================================================
8 rebol code REBOL [
9 rebol code Title: "Change File Extensions (Suffix)"
10 rebol code File: %new-suffix.r
11 rebol code Author: "Carl Sassenrath"
12 rebol code Date: 25-Jan-2005
13 rebol code Purpose: {
14 rebol code Change the file extension (suffix) for files with a specific extension.
15 rebol code For example, change all .txt files to .r files in the current directory.
16 rebol code Displays a list of changes before it makes them.
17 rebol code }
18 rebol code Warning: "Back up your files first, just in case!"
19 rebol code License: "BSD - Use at your own risk."
20 rebol code Library: [
21 rebol code level: 'beginner
22 rebol code platform: 'all
23 rebol code type: [tool]
24 rebol code domain: [files]
25 rebol code tested-under: none
26 rebol code support: none
27 rebol code license: 'bsd
28 rebol code see-also: none
29 rebol code ]
30 rebol code ]
31 rebol blank
32 rebol code from-suffix: %.txt
33 rebol code to-suffix: %.r
34 rebol blank
35 rebol code bulk-rename: func [confirmed] [
36 rebol code foreach file load %./ [
37 rebol code if all [
38 rebol code not find file #"/" ; (ignore directories)
39 rebol code from-suffix = find/last file #"."
40 rebol code ][
41 rebol code new-file: copy file
42 rebol code append clear find/last new-file #"." to-suffix
43 rebol code either confirmed [
44 rebol code print ["Renaming" file "to" new-file]
45 rebol code rename file new-file
46 rebol code ][
47 rebol code print ["Will rename" file "to" new-file]
48 rebol code ]
49 rebol code ]
50 rebol code ]
51 rebol code ]
52 rebol blank
53 rebol code bulk-rename false
54 rebol code if not confirm "Are you sure you want to rename all those files?" [
55 rebol code quit
56 rebol code ]
57 rebol code bulk-rename true
58 rebol code ask "Done. Press enter."
0 rust comment /*
1 rust comment * This is the example given by www.rust-lang.org
2 rust comment */
3 rust comment // Line comments work too
4 rust code fn main() {
5 rust code let nums = [1, 2];
6 rust code let noms = ["Tim", "Eston", "Aaron", "Ben"];
7 rust blank
8 rust code let mut odds = nums.iter().map(|&x| x * 2 - 1);
9 rust blank
10 rust code for num in odds {
11 rust code do spawn {
12 rust code println!("{:s} says hello from a lightweight thread!", noms[num]);
13 rust code }
14 rust code }
15 rust code }
0 modula3 code (* Modula-3 *) INTERFACE M3Sample; (* file extension ".i3" *)
1 modula3 blank
2 modula3 comment (* This is a comment *)
3 modula3 blank
4 modula3 comment (* This is a comment ...
5 modula3 comment ... spanning more than one line *)
6 modula3 blank
7 modula3 code CONST
8 modula3 code sqString = 'this is a string within "a string" ...\n';
9 modula3 code dqString = "this is a string within 'a string' ...\n";
10 modula3 blank
11 modula3 code END M3Sample.
0 modula3 code (* Modula-3 *) MODULE M3Sample; (* file extension ".m3" *)
1 modula3 blank
2 modula3 comment (* This is a comment *)
3 modula3 blank
4 modula3 comment (* This is a comment ...
5 modula3 comment ... spanning more than one line *)
6 modula3 blank
7 modula3 code CONST
8 modula3 code sqString = 'this is a string within "a string" ...\n';
9 modula3 code dqString = "this is a string within 'a string' ...\n";
10 modula3 blank
11 modula3 code END M3Sample.
0 modula2 code MODULE Sample; (* in Modula-2 *)
1 modula2 blank
2 modula2 comment (* This is a comment *)
3 modula2 blank
4 modula2 comment (* This is a comment ...
5 modula2 comment ... spanning more than one line *)
6 modula2 blank
7 modula2 code CONST
8 modula2 code sqString = 'this is a string within "a string" ...';
9 modula2 code dqString = "this is a string within 'a string' ...";
10 modula2 blank
11 modula2 code END Sample.
0 oberon code (* Oberon-2 *) MODULE OberonSample; (* file extension ".ob2" *)
1 oberon blank
2 oberon comment (* This is a comment *)
3 oberon blank
4 oberon comment (* This is a comment ...
5 oberon comment ... spanning more than one line *)
6 oberon blank
7 oberon code CONST
8 oberon code sqString* = 'this is a string within "a string" ...';
9 oberon code dqString* = "this is a string within 'a string' ...";
10 oberon blank
11 oberon code END OberonSample.
0 oberon code (* Oberon *) MODULE OberonSample; (* file extension ".obn" *)
1 oberon blank
2 oberon comment (* This is a comment *)
3 oberon blank
4 oberon comment (* This is a comment ...
5 oberon comment ... spanning more than one line *)
6 oberon blank
7 oberon code CONST
8 oberon code sqString* = 'this is a string within "a string" ...';
9 oberon code dqString* = "this is a string within 'a string' ...";
10 oberon blank
11 oberon code END OberonSample.
0 modula2 code DEFINITION MODULE Sample; (* in Modula-2 *)
1 modula2 blank
2 modula2 comment (* This is a comment *)
3 modula2 blank
4 modula2 comment (* This is a comment ...
5 modula2 comment ... spanning more than one line *)
6 modula2 blank
7 modula2 code CONST
8 modula2 code sqString = 'this is a string within "a string" ...';
9 modula2 code dqString = "this is a string within 'a string' ...";
10 modula2 blank
11 modula2 code END Sample.
0 modula2 code IMPLEMENTATION MODULE Sample; (* in Modula-2 *)
1 modula2 blank
2 modula2 comment (* This is a comment *)
3 modula2 blank
4 modula2 comment (* This is a comment ...
5 modula2 comment ... spanning more than one line *)
6 modula2 blank
7 modula2 code CONST
8 modula2 code sqString = 'this is a string within "a string" ...';
9 modula2 code dqString = "this is a string within 'a string' ...";
10 modula2 blank
11 modula2 code END Sample.
0 shell code var="\
1 shell code Some string"
2 shell blank
3 shell comment # Now a comment
4 shell code var="some new string"
0 typescript comment /*
1 typescript comment * This is a TypeScript File
2 typescript comment */
3 typescript blank
4 typescript comment // And a regular comment
5 typescript blank
6 typescript code export class SomeClass {
7 typescript code public text: string;
8 typescript blank
9 typescript code public sayHello(name: string): string {
10 typescript code return `Hello, ${name}`;
11 typescript code }
12 typescript code }
13 typescript blank
0 /* This is a test file for AMPL
1 * This is a multiline comment
2 */
3
4 # An AMPL model
5 var x >= 42; # variable definition.
6 minimize o: x;
0 ; "Hello world" in 6502 assembly language for 8-bit Atari.
1 ; Assembler: http://xasm.atari.org/ or http://mads.atari8.info/
2
3 org $3000
4 main lda #$21
5 sta $22f
6 lda #<dl
7 sta $230
8 lda #>dl
9 sta $231
10 jmp *
11
12 text dta d' HELLO, ',d'WORLD! '*
13
14 ; Display List
15 dl dta b($70),b($70),b($70),b($47),a(text),b($41),a(dl)
16
17 org $2e0
18 dta a(main)
19
20 end
0 ; "Hello world" in 6502 assembly language for 8-bit Atari.
1 ; Assembler: http://xasm.atari.org/ or http://mads.atari8.info/
2
3 org $3000
4 main lda #$21
5 sta $22f
6 lda #<dl
7 sta $230
8 lda #>dl
9 sta $231
10 jmp *
11
12 text dta d' HELLO, ',d'WORLD! '*
13
14 ; Display List
15 dl dta b($70),b($70),b($70),b($47),a(text),b($41),a(dl)
16
17 org $2e0
18 dta a(main)
19
20 end
0 (** documentation *)
1 module Augeas =
2 autoload xfm
3 (**/**)
4 (* extra comment *)
5
6 (* multiline
7 comment*)
8 let lns = Shellvars.lns
9
10 (* recursion in (* a
11 comment *) to complicate things *)
12 let filter = incl "/foo/bar"
13 let xfm = transform lns filter
0
1 = comment
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 = [-] is used to clear a cell
35
36 = Try to open b file
37 >+++++++[>+++++++[<<++>>-]<-]<.
38 #[
39 >>++++[<++++>-]<+[<++++++>-]<.
40 +++.
41 +++.
42 -------.
43 >>++++[<++++++>-]<-[<--->-]<.
44 >>++[<+++++>-]<+[<++++++>-]<.
45 >>++[<+++++>-]<+[<------>-]<.
46 >>++++[<++++++>-]<++[<+++>-]<+.
47 +.
48 >++[<----->-]<-.
49 >+++[<+++>-]<.
50 >+++[<--->-]<.
51 -.
52 #]
53 @include(nothing.bfpp)
00 REM comment 1
11 rem comment 2
22 rEm comment 3
3 rEm.comment 4
4 Rem=comment 5
5 @Rem comment 6
6 @reM=comment 7
7 ::comment 8
38
49 echo not a rem comment!
510
0 Print "Hello World!!!!!"
1
2 Line that does nothing: ><
3 >++++++[>+++[<<++++>>-]<-]<.
4 >+++++[<++++++>-]<-.
5 +++++++.
6 .
7 +++.
8 >>++++[<++++++>-]<++[<--->-]<-.
9 >>++[<+++++>-]<+[<+++++>-]<.
10 >++++[<++++++>-]<.
11 +++.
12 ------.
13 >++[<---->-]<.
14 >>++[<+++++>-]<+[<------>-]<-.
15 .
16 .
17 .
18 .
0 /*
1 Random Comments
2 Foo Foo Foo
3 */
4 var submenu=1;
5 // comment
6 // another comment
7 submenu += 10
8 var f = fun() { 5 };
9 def myFun(i) : i > 0 {
10 return i + 10;
11 }
12
13
14 // some comment
15 var delay_hide=500
16 b=0
0 ;;; Copyright (C) 2009 Brendan Ribera. All rights reserved.
1 ;;; Distributed under the MIT License; see the file LICENSE
2 ;;; at the root of this distribution.
3 (ns kdtree)
4
5 (defn dist-squared [a b]
6 "Compute the K-dimensional distance between two points"
7 (reduce + (for [i (range (count a))]
8 (let [v (- (nth a i)
9 (nth b i))]
10 (* v v)))))
11
12 ;;; Simple accessors
13 (defn- node-value [n] (first n))
14 (defn- node-left [n] (first (rest n)))
15 (defn- node-right [n] (first (rest (rest n))))
0 #include <unistd.h>
1 #include <error.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <errno.h>
5 #include <assert.h>
6
7 #include "components.h"
8 #include "common.h"
9
10 #define THREADS 256
11
12 /* Store 3 RGB float components */
13 __device__ void storeComponents(float *d_r, float *d_g, float *d_b, float r, float g, float b, int pos)
14 {
15 d_r[pos] = (r/255.0f) - 0.5f;
16 d_g[pos] = (g/255.0f) - 0.5f;
17 d_b[pos] = (b/255.0f) - 0.5f;
18 }
19
20 /* Store 3 RGB intege components */
21 __device__ void storeComponents(int *d_r, int *d_g, int *d_b, int r, int g, int b, int pos)
22 {
23 d_r[pos] = r - 128;
24 d_g[pos] = g - 128;
25 d_b[pos] = b - 128;
26 }
0 Require Import String.
1 (* comment *)
2 Check "multiline
3 string"%string.
4
5 (* multiline
6 comment *)
7
8 (* recursion in (* a
9 comment *) to complicate things *)
0 // Just an example of QML file...
1
2 import QtQuick 2.0
3
4 Rectangle {
5 width: 200
6 height: 200
7 color: "crimson"
8
9 MouseArea {
10 anchors.fill: parent
11 onClicked: {
12 // Was clicked
13 Qt.quit();
14 }
15 }
16 }
0 ;; language declaration commented out until someone extends the
1 ;; parser to support it:
2
3 ;; #lang racket
4
5 ;; Report each unique line from stdin
6 (let ([saw (make-hash)])
7 (for ([line (in-lines)])
8 (unless (hash-ref saw line #f)
9 (displayln line))
10 (hash-set! saw line #t)))
11
0 # A CoffeeScript parser test file
1
2 simple_code = true
3
4 ###
5 A multi-line block comment
6 begins and ends with three hash marks
7 ###
8
9 multi_line_string = '''
10 A multi-line string constant ("here doc")
11 begins and ends with three quote marks
12 '''
13
14 foo = "A string can wrap across multiple lines
15 and may contain #{interpolated_values}"
16
17
18 ###
19 A clever parser can use Ohcount's "Polyglot" feature treat the
20 following as embedded JavaScript.
21 ###
22 embedded_js = `function() {
23 return [document.title, "Hello JavaScript"].join(": ");
24 }`
25
0 \begin{document}
1 \texbf Hello world
2
3
4 % \acommand
5 % \anothercommand
6 %% sample comment
7
8 \end{document}
0 ; NSIS "header" libraries can be in .nsh files.
1 /* Copyright some time
2 * never
3 * and not much of that either
4 "still a comment"
5 */
6
7 !macro SillyMacro Param1
8 ; ... Because we can ;-)
9 !error "Why did you call this macro, ${Param1}? That was silly."
10 !macroend
11
12 Function Die
13 # Likewise, because we can.
14 DetailPrint "Aarrrrggghh! I died."
15 Quit
16 FunctionEnd
0 ; some nsis code
1 /*
2 * lorem
3 ipsum
4 dolor sit amet etcetera
5 */
6
7 !include LogicLib.nsh
8 OutFile foo.exe
9
10 Section
11 IfFileExists ${__FILE__} 0 +2 ; comments can be inline
12 # Use of ; in a string on the next line
13 MessageBox MB_OK "You moved this installer file; you shouldn't do that ;-)"
14 SectionEnd
0 \ Sample Forth code
1
2 ( This is a comment
3 spanning multiple lines )
4
5 : somedefinition ;
6
0 //////////////////////////////////////////////////
1 // Sample Grace code
2
3 import "parsers-test" as parsers
4
5 class exports {
6 inherit parsers.exports
7 //BEGINGRAMMAR
8 // top level
9 def program = rule {codeSequence ~ rep(ws) ~ end}
10 def codeSequence = rule { repdel((declaration | statement | empty), semicolon) }
11 def hashLine = rule { (symbol "#") ~ rep(anyChar | space) ~ (newLine | end) }
12
13 // def comment =
14
15 //def oldClassDeclaration = rule { classId ~ identifier ~ lBrace ~
16 // opt(genericFormals ~ blockFormals ~ arrow) ~ codeSequence ~ rBrace }
17
18 def typeOpExpression = rule { rep1sep(basicTypeExpression, typeOp) }
19
20 def typeOpExpression = rule {
21 var otherOperator
22 basicTypeExpression ~ opt(ws) ~
23 opt( guard(typeOp, { s -> otherOperator:= s;
24 true }) ~ rep1sep(basicTypeExpression ~ opt(ws),
25 guard(typeOp, { s -> s == otherOperator })
26 )
27 )
28 }
29
30 // "literals"
31 def literal = rule { stringLiteral | selfLiteral | blockLiteral | numberLiteral | objectLiteral | lineupLiteral | typeLiteral }
32
33 // terminals
34 def backslash = token "\\" // doesn't belong here, doesn't work if left below!
35
36 def colon = rule {both(symbol ":", not(assign))}
37 def newLine = symbol "\n"
38 def lParen = symbol "("
39 def rParen = symbol ")"
40
41 def reservedOp = rule {assign | equals | dot | arrow | colon | semicolon} // this is not quite right
42
43 //ENDGRAMMAR
44 }
45
0 #!/usr/bin/perl -w
1
2 # ajaxCheckbox.pl - a script to test Ajax functionality
3
4 use strict;
5 use CGI qw/:standard/;
6 use CGI::Ajax;
7 use DBI;
8
9 # --- database authenication
10 my $dbh = do 'db.inc';
11
12 my $query = q{ SELECT project.project_id, project.name, project.phase, prio.prio,
13 HEX((255 - prio.prio)) AS hex, begun, tags
14 FROM project JOIN prio
15 ON (project.project_id = prio.project_id)
16 WHERE completed < 1
17 ORDER BY prio.prio DESC LIMIT 3};
18
19 my $sth = $dbh->prepare($query);
20 $sth->execute();
21 my $result = $dbh->selectall_arrayref($sth);
22
23 my $cgi = new CGI;
24 my $pjx = new CGI::Ajax( 'toStruck' => \&perl_func );
25 print $pjx->build_html( $cgi, \&Show_HTML);
26
27 sub Show_HTML {
28
29 use CGI qw/:standard/;
30
31 my $html = <<HEAD;
32 <!DOCTYPE html
33 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
34 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
35 <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
36 <head>
37 <title>This is the lastest source version</title>
38 <link rel="stylesheet" type="text/css" href="/css/carrot.css" />
39 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
40 </head><body>
41 <h2>Carrot Queue</h2><a href="/cgi-bin/source_carrot/index.cgi">Priority List</a><b>&nbsp; | &nbsp;</b>
42 <a href="/cgi-bin/source_carrot/add.cgi">Add a listing</a><b>&nbsp; | &nbsp;</b><div class="content" /><h4>Project listing</h4>
43 HEAD
44
45 foreach my $row (@$result) {
46 $html .= "<input type=\"checkbox\" name=name" . @$row[0] . " id=val" . @$row[0] . " value=\"ON\" onClick=\"toStruck( ['val@$row[0]'], ['div@$row[0]'] );\">";
47 $html .= "<div id=\"div@$row[0]\" style=\"display: inline;\"><!-- This gets entirely replaced -->" . @$row[1] . "</span></div><br>";
48 }
49
50 # you can append stuff to the HTML this way
51 $html .= "</body></html>";
52
53 return $html;
54 }
55
56 sub perl_func {
57 my $input=shift;
58
59 # if onClick the change the style
60 if ($input eq "ON") {
61 $input="<span style=\"text-decoration: line-through; display: inline;\">";
62 } else {
63 $input ="<span style=\"text-decoration: none; display: inline;\">";
64 }
65 }
0 /* test file for Logtalk parsing */
1
2 % this is a Logtalk source file
3
4 :- object(hello_world).
5
6 % the initialization/1 directive argument is automatically executed
7 % when the object is loaded into memory:
8 :- initialization((nl, write('********** Hello World! **********'), nl)).
9
10 :- end_object.
0
1 SetEnhancedTimes[False];
2 SetSourceLanguage["C"];
3
4 (******************************************************************************)
5 (* Options *)
6 (******************************************************************************)
7
8 createCode[derivOrder_, useJacobian_, splitUpwindDerivs_, useVectors_, useOpenCL_, evolutionTimelevels_, addMatter_, formulation_] :=
9 Module[{prefix, suffix, thorn},
10
11 prefix = "ML_";
12 suffix =
13 ""
14 <> If [useJacobian, "_MP", ""]
15 <> If [derivOrder!=4, "_O" <> ToString[derivOrder], ""]
16 <> If [splitUpwindDerivs, "", "_UPW"]
17 <> If [useVectors, "", "_NV"]
18 <> If [useOpenCL, "_CL", ""]
19 (* <> If [evolutionTimelevels!=3, "_TL" <> ToString[evolutionTimelevels], ""] *)
20 (* <> If [addMatter==1, "_M", ""] *)
21 ;
22
23 thorn = prefix <> formulation <> suffix;
24
25 SetAttributes[IfCCZ4, HoldAll];
26 IfCCZ4[expr_, else_:Sequence[]] := If[formulation === "CCZ4", expr, Unevaluated[else]];
27
28 (******************************************************************************)
29 (* Derivatives *)
30 (******************************************************************************)
31
32 KD = KroneckerDelta;
33
34 derivatives =
35 {
36 PDstandardNth[i_] -> StandardCenteredDifferenceOperator[1,fdOrder/2,i],
37 PDstandardNth[i_,i_] -> StandardCenteredDifferenceOperator[2,fdOrder/2,i],
38 PDstandardNth[i_,j_] -> StandardCenteredDifferenceOperator[1,fdOrder/2,i] *
39 StandardCenteredDifferenceOperator[1,fdOrder/2,j],
40 PDdissipationNth[i_] ->
41 (-1)^(fdOrder/2) *
42 spacing[i]^(fdOrder+1) / 2^(fdOrder+2) *
43 StandardCenteredDifferenceOperator[fdOrder+2,fdOrder/2+1,i],
44
45 (* PD: These come from my mathematica notebook
46 "Upwind-Kranc-Convert.nb" that converts upwinding finite
47 differencing operators generated by
48 StandardUpwindDifferenceOperator into this form *)
49
50 Sequence@@Flatten[Table[
51 {PDupwindNth[i] -> Switch[fdOrder,
52 2, (dir[i]*(-3 + 4*shift[i]^dir[i] - shift[i]^(2*dir[i])))/(2*spacing[i]),
53 4, (dir[i]*(-10 - 3/shift[i]^dir[i] + 18*shift[i]^dir[i] -
54 6*shift[i]^(2*dir[i]) + shift[i]^(3*dir[i])))/(12*spacing[i]),
55 6, (dir[i]*(-35 + 2/shift[i]^(2*dir[i]) - 24/shift[i]^dir[i] + 80*shift[i]^dir[i] -
56 30*shift[i]^(2*dir[i]) + 8*shift[i]^(3*dir[i]) - shift[i]^(4*dir[i])))/(60*spacing[i]),
57 8, (dir[i]*(-378 - 5/shift[i]^(3*dir[i]) + 60/shift[i]^(2*dir[i]) - 420/shift[i]^dir[i] +
58 1050*shift[i]^dir[i] - 420*shift[i]^(2*dir[i]) + 140*shift[i]^(3*dir[i]) - 30*shift[i]^(4*dir[i]) +
59 3*shift[i]^(5*dir[i])))/(840*spacing[i])],
60
61 PDupwindNthAnti[i] -> Switch[fdOrder,
62 2, (+1 shift[i]^(-2) -4 shift[i]^(-1) +0 shift[i]^( 0) +4 shift[i]^(+1) -1 shift[i]^(+2)) / (4 spacing[i]),
63 4, (-1 shift[i]^(-3) +6 shift[i]^(-2) -21 shift[i]^(-1 )+0 shift[i]^( 0) +21 shift[i]^(+1)
64 -6 shift[i]^(+2) +1 shift[i]^(+3)) / (24 spacing[i]),
65 6, (+1 shift[i]^(-4) -8 shift[i]^(-3) +32 shift[i]^(-2) -104 shift[i]^(-1) +0 shift[i]^( 0)
66 +104 shift[i]^(+1) -32 shift[i]^(+2) +8 shift[i]^(+3) -1 shift[i]^(+4)) / (120 spacing[i]),
67 8, (-3 shift[i]^(-5) +30 shift[i]^(-4) -145 shift[i]^(-3) +480 shift[i]^(-2) -1470 shift[i]^(-1)
68 +0 shift[i]^( 0) +1470 shift[i]^(+1) -480 shift[i]^(+2) +145 shift[i]^(+3) -30 shift[i]^(+4)
69 +3 shift[i]^(+5)) / (1680 spacing[i])],
70
71 PDupwindNthSymm[i] -> Switch[fdOrder,
72 2, (-1 shift[i]^(-2) +4 shift[i]^(-1) -6 shift[i]^( 0) +4 shift[i]^(+1) -1 shift[i]^(+2)) / (4 spacing[i]),
73 4, (+1 shift[i]^(-3) -6 shift[i]^(-2) +15 shift[i]^(-1) -20 shift[i]^( 0) +15 shift[i]^(+1)
74 -6 shift[i]^(+2) +1 shift[i]^(+3)) / (24 spacing[i]),
75 6, (-1 shift[i]^(-4) +8 shift[i]^(-3) - 28 shift[i]^(-2)+56 shift[i]^(-1)-70 shift[i]^( 0)
76 +56 shift[i]^(+1) -28 shift[i]^(+2) +8 shift[i]^(+3) -1 shift[i]^(+4)) / (120 spacing[i]),
77 8, (+3 shift[i]^(-5) -30 shift[i]^(-4) +135 shift[i]^(-3) -360 shift[i]^(-2) +630 shift[i]^(-1)
78 -756 shift[i]^( 0) +630 shift[i]^(+1) -360 shift[i]^(+2) +135 shift[i]^(+3) -30 shift[i]^(+4)
79 +3 shift[i]^(+5)) / (1680 spacing[i])],
80
81 (* TODO: make these higher order stencils *)
82 PDonesided[i] -> dir[i] (-1 + shift[i]^dir[i]) / spacing[i]} /. i->j, {j,1,3}],1]
83 };
84
85 PD = PDstandardNth;
86 PDu = PDupwindNth;
87 PDua = PDupwindNthAnti;
88 PDus = PDupwindNthSymm;
89 (* PDo = PDonesided; *)
90 PDdiss = PDdissipationNth;
91
92 If [splitUpwindDerivs,
93 Upwind[dir_, var_, idx_] := dir PDua[var,idx] + Abs[dir] PDus[var,idx],
94 Upwind[dir_, var_, idx_] := dir PDu[var,idx]];
95
96
97
98 (******************************************************************************)
99 (* Tensors *)
100 (******************************************************************************)
101
102 (* Register the tensor quantities with the TensorTools package *)
103 Map [DefineTensor,
104 {normal, tangentA, tangentB, dir,
105 nn, nu, nlen, nlen2, su, vg,
106 xx, rr, th, ph,
107 admg, admK, admalpha, admdtalpha, admbeta, admdtbeta, H, M,
108 g, detg, gu, G, R, trR, Km, trK, cdphi, cdphi2,
109 phi, gt, At, Xt, Xtn, Theta, Z,
110 alpha, A, beta, B, Atm, Atu, trA, Ats, trAts,
111 dottrK, dotXt,
112 cXt, cS, cA,
113 e4phi, em4phi, ddetg, detgt, gtu, ddetgt, dgtu, ddgtu, Gtl, Gtlu, Gt,
114 Rt, Rphi, gK,
115 T00, T0, T, rho, S,
116 x, y, z, r,
117 epsdiss}];
118
119 (* NOTE: It seems as if Lie[.,.] did not take these tensor weights
120 into account. Presumably, CD[.,.] and CDt[.,.] don't do this either. *)
121 SetTensorAttribute[phi, TensorWeight, +1/6];
122 SetTensorAttribute[gt, TensorWeight, -2/3];
123 SetTensorAttribute[Xt, TensorWeight, +2/3];
124 SetTensorAttribute[At, TensorWeight, -2/3];
125 SetTensorAttribute[cXt, TensorWeight, +2/3];
126 SetTensorAttribute[cS, TensorWeight, +2 ];
127
128 Map [AssertSymmetricIncreasing,
129 {admg[la,lb], admK[la,lb], g[la,lb], K[la,lb], R[la,lb], cdphi2[la,lb],
130 gt[la,lb], At[la,lb], Ats[la,lb], Rt[la,lb], Rphi[la,lb], T[la,lb]}];
131 AssertSymmetricIncreasing [G[ua,lb,lc], lb, lc];
132 AssertSymmetricIncreasing [Gtl[la,lb,lc], lb, lc];
133 AssertSymmetricIncreasing [Gt[ua,lb,lc], lb, lc];
134 AssertSymmetricIncreasing [gK[la,lb,lc], la, lb];
135 Map [AssertSymmetricIncreasing,
136 {gu[ua,ub], gtu[ua,ub], Atu[ua,ub]}];
137 AssertSymmetricIncreasing [dgtu[ua,ub,lc], ua, ub];
138 AssertSymmetricIncreasing [ddgtu[ua,ub,lc,ld], ua, ub];
139 AssertSymmetricIncreasing [ddgtu[ua,ub,lc,ld], lc, ld];
140
141 DefineConnection [CD, PD, G];
142 DefineConnection [CDt, PD, Gt];
143
144 (* Use the CartGrid3D variable names *)
145 x1=x; x2=y; x3=z;
146
147 (* Use the ADMBase variable names *)
148 admg11=gxx; admg12=gxy; admg22=gyy; admg13=gxz; admg23=gyz; admg33=gzz;
149 admK11=kxx; admK12=kxy; admK22=kyy; admK13=kxz; admK23=kyz; admK33=kzz;
150 admalpha=alp;
151 admdtalpha=dtalp;
152 admbeta1=betax; admbeta2=betay; admbeta3=betaz;
153 admdtbeta1=dtbetax; admdtbeta2=dtbetay; admdtbeta3=dtbetaz;
154
155 (* Use the TmunuBase variable names *)
156 T00=eTtt;
157 T01=eTtx; T02=eTty; T03=eTtz;
158 T11=eTxx; T12=eTxy; T22=eTyy; T13=eTxz; T23=eTyz; T33=eTzz;
159
160
161
162 (******************************************************************************)
163 (* Expressions *)
164 (******************************************************************************)
165
166 (* enum constants for conformalMethod; these must be consistent
167 with the definition of the Cactus parameter conformalMethod *)
168 CMphi = 0;
169 CMW = 1;
170
171 detgExpr = Det [MatrixOfComponents [g [la,lb]]];
172 ddetgExpr[la_] =
173 Sum [D[Det[MatrixOfComponents[g[la, lb]]], X] PD[X, la],
174 {X, Union[Flatten[MatrixOfComponents[g[la, lb]]]]}];
175
176 detgtExpr = Det [MatrixOfComponents [gt[la,lb]]];
177 ddetgtExpr[la_] =
178 Sum [D[Det[MatrixOfComponents[gt[la, lb]]], X] PD[X, la],
179 {X, Union[Flatten[MatrixOfComponents[gt[la, lb]]]]}];
180
181 etaExpr = SpatialBetaDriverRadius / Max [r, SpatialBetaDriverRadius];
182 thetaExpr = Min [Exp [1 - r / SpatialShiftGammaCoeffRadius], 1];
183
184
185
186 (******************************************************************************)
187 (* Groups *)
188 (******************************************************************************)
189
190 evolvedGroups =
191 {SetGroupName [CreateGroupFromTensor [phi ], prefix <> "log_confac"],
192 SetGroupName [CreateGroupFromTensor [gt[la,lb]], prefix <> "metric" ],
193 SetGroupName [CreateGroupFromTensor [Xt[ua] ], prefix <> "Gamma" ],
194 SetGroupName [CreateGroupFromTensor [trK ], prefix <> "trace_curv"],
195 SetGroupName [CreateGroupFromTensor [At[la,lb]], prefix <> "curv" ],
196 SetGroupName [CreateGroupFromTensor [alpha ], prefix <> "lapse" ],
197 SetGroupName [CreateGroupFromTensor [A ], prefix <> "dtlapse" ],
198 SetGroupName [CreateGroupFromTensor [beta[ua] ], prefix <> "shift" ],
199 SetGroupName [CreateGroupFromTensor [B[ua] ], prefix <> "dtshift" ],
200 IfCCZ4[SetGroupName[CreateGroupFromTensor[Theta], prefix <> "Theta"]]};
201 evaluatedGroups =
202 {SetGroupName [CreateGroupFromTensor [H ], prefix <> "Ham"],
203 SetGroupName [CreateGroupFromTensor [M[la] ], prefix <> "mom"],
204 SetGroupName [CreateGroupFromTensor [cS ], prefix <> "cons_detg"],
205 SetGroupName [CreateGroupFromTensor [cXt[ua]], prefix <> "cons_Gamma"],
206 SetGroupName [CreateGroupFromTensor [cA ], prefix <> "cons_traceA"]};
207
208 declaredGroups = Join [evolvedGroups, evaluatedGroups];
209 declaredGroupNames = Map [First, declaredGroups];
210
211
212
213 extraGroups =
214 {{"grid::coordinates", {x, y, z, r}},
215 {"ADMBase::metric", {gxx, gxy, gxz, gyy, gyz, gzz}},
216 {"ADMBase::curv", {kxx, kxy, kxz, kyy, kyz, kzz}},
217 {"ADMBase::lapse", {alp}},
218 {"ADMBase::dtlapse", {dtalp}},
219 {"ADMBase::shift", {betax, betay, betaz}},
220 {"ADMBase::dtshift", {dtbetax, dtbetay, dtbetaz}},
221 {"TmunuBase::stress_energy_scalar", {eTtt}},
222 {"TmunuBase::stress_energy_vector", {eTtx, eTty, eTtz}},
223 {"TmunuBase::stress_energy_tensor", {eTxx, eTxy, eTxz, eTyy, eTyz, eTzz}}
224 };
225
226 groups = Join [declaredGroups, extraGroups];
227
228
229
230 (******************************************************************************)
231 (* Initial data *)
232 (******************************************************************************)
233
234 initialCalc =
235 {
236 Name -> thorn <> "_Minkowski",
237 Schedule -> {"IN ADMBase_InitialData"},
238 ConditionalOnKeyword -> {"my_initial_data", "Minkowski"},
239 Equations ->
240 {
241 phi -> IfThen[conformalMethod==CMW, 1, 0],
242 gt[la,lb] -> KD[la,lb],
243 trK -> 0,
244 At[la,lb] -> 0,
245 Xt[ua] -> 0,
246 alpha -> 1,
247 A -> 0,
248 beta[ua] -> 0,
249 B[ua] -> 0,
250 IfCCZ4[Theta -> 0]
251 }
252 };
253
254
255
256 (******************************************************************************)
257 (* Split a calculation *)
258 (******************************************************************************)
259
260 PartialCalculation[calc_, suffix_, updates_, evolVars_] :=
261 Module[
262 {name, calc1, replaces, calc2, vars, patterns, eqs, calc3},
263 (* Add suffix to name *)
264 name = lookup[calc, Name] <> suffix;
265 calc1 = mapReplace[calc, Name, name];
266 (* Replace some entries in the calculation *)
267 (* replaces = Map[Function[rule, mapReplace[#, rule[[1]], rule[[2]]]&], updates]; *)
268 replaces = updates //. (lhs_ -> rhs_) -> (mapReplace[#, lhs, rhs]&);
269 calc2 = Apply[Composition, replaces][calc1];
270 (* Remove unnecessary equations *)
271 vars = Join[evolVars, lookup[calc2, Shorthands]];
272 patterns = Replace[vars, { Tensor[n_,__] -> Tensor[n,__] ,
273 dot[Tensor[n_,__]] -> dot[Tensor[n,__]]}, 1];
274 eqs = FilterRules[lookup[calc, Equations], patterns];
275 calc3 = mapReplace[calc2, Equations, eqs];
276 calc3
277 ];
278
279
280
281 (******************************************************************************)
282 (* Convert from ADMBase *)
283 (******************************************************************************)
284
285 convertFromADMBaseCalc =
286 {
287 Name -> thorn <> "_convertFromADMBase",
288 Schedule -> {"AT initial AFTER ADMBase_PostInitial"},
289 ConditionalOnKeyword -> {"my_initial_data", "ADMBase"},
290 Shorthands -> {g[la,lb], detg, gu[ua,ub], em4phi},
291 Equations ->
292 {
293 g[la,lb] -> admg[la,lb],
294 detg -> detgExpr,
295 gu[ua,ub] -> 1/detg detgExpr MatrixInverse [g[ua,ub]],
296
297 phi -> IfThen[conformalMethod==CMW, detg^(-1/6), Log[detg]/12],
298 em4phi -> IfThen[conformalMethod==CMW, phi^2, Exp[-4 phi]],
299 gt[la,lb] -> em4phi g[la,lb],
300
301 trK -> gu[ua,ub] admK[la,lb],
302 At[la,lb] -> em4phi (admK[la,lb] - (1/3) g[la,lb] trK),
303
304 alpha -> admalpha,
305
306 beta[ua] -> admbeta[ua],
307
308 IfCCZ4[Theta -> 0]
309 }
310 };
311
312 convertFromADMBaseGammaCalc =
313 {
314 Name -> thorn <> "_convertFromADMBaseGamma",
315 Schedule -> {"AT initial AFTER " <> thorn <> "_convertFromADMBase"},
316 ConditionalOnKeyword -> {"my_initial_data", "ADMBase"},
317 (*
318 Where -> InteriorNoSync,
319 *)
320 (* Do not synchronise right after this routine; instead, synchronise
321 after extrapolating *)
322 Where -> Interior,
323 (* Synchronise after this routine, so that the refinement boundaries
324 are set correctly before extrapolating. (We will need to
325 synchronise again after extrapolating because extrapolation does
326 not fill ghost zones, but this is irrelevant here.) *)
327 Shorthands -> {dir[ua],
328 detgt, gtu[ua,ub], Gt[ua,lb,lc], theta},
329 Equations ->
330 {
331 dir[ua] -> Sign[beta[ua]],
332
333 detgt -> 1 (* detgtExpr *),
334 gtu[ua,ub] -> 1/detgt detgtExpr MatrixInverse [gt[ua,ub]],
335 Gt[ua,lb,lc] -> 1/2 gtu[ua,ud]
336 (PD[gt[lb,ld],lc] + PD[gt[lc,ld],lb] - PD[gt[lb,lc],ld]),
337 Xt[ua] -> gtu[ub,uc] Gt[ua,lb,lc],
338
339 (*
340 A -> - admdtalpha / (harmonicF alpha^harmonicN) (LapseAdvectionCoeff - 1),
341 *)
342 (* If LapseACoeff=0, then A is not evolved, in the sense that it
343 does not influence the time evolution of other variables. *)
344 A -> IfThen [LapseACoeff != 0,
345 1 / (- harmonicF alpha^harmonicN)
346 (+ admdtalpha
347 - LapseAdvectionCoeff Upwind[beta[ua], alpha, la]),
348 0],
349
350 theta -> thetaExpr,
351
352 (* If ShiftBCoeff=0 or theta ShiftGammaCoeff=0, then B^i is not
353 evolved, in the sense that it does not influence the time
354 evolution of other variables. *)
355 B[ua] -> IfThen [ShiftGammaCoeff ShiftBCoeff != 0,
356 1 / (theta ShiftGammaCoeff)
357 (+ admdtbeta[ua]
358 - ShiftAdvectionCoeff Upwind[beta[ub], beta[ua], lb]),
359 0]
360 }
361 };
362
363 (* Initialise the Gamma variables to 0. This is necessary with
364 multipatch because convertFromADMBaseGamma does not perform the
365 conversion in the boundary points, and the order in which symmetry
366 (interpatch) and outer boundary conditions is applied means that
367 points which are both interpatch and symmetry points are never
368 initialised. *)
369 initGammaCalc =
370 {
371 Name -> thorn <> "_InitGamma",
372 Schedule -> {"AT initial BEFORE " <> thorn <> "_convertFromADMBaseGamma"},
373 ConditionalOnKeyword -> {"my_initial_data", "ADMBase"},
374 Where -> Everywhere,
375 Equations ->
376 {
377 Xt[ua] -> 0,
378 A -> 0,
379 B[ua] -> 0
380 }
381 };
382
383
384
385 (******************************************************************************)
386 (* Convert to ADMBase *)
387 (******************************************************************************)
388
389 convertToADMBaseCalc =
390 {
391 Name -> thorn <> "_convertToADMBase",
392 Schedule -> {"IN " <> thorn <> "_convertToADMBaseGroup"},
393 Where -> Everywhere,
394 Shorthands -> {e4phi},
395 Equations ->
396 {
397 e4phi -> IfThen[conformalMethod==CMW, 1/phi^2, Exp[4 phi]],
398 admg[la,lb] -> e4phi gt[la,lb],
399 admK[la,lb] -> e4phi At[la,lb] + (1/3) admg[la,lb] trK,
400 admalpha -> alpha,
401 admbeta[ua] -> beta[ua]
402 }
403 };
404
405 convertToADMBaseDtLapseShiftCalc =
406 {
407 Name -> thorn <> "_convertToADMBaseDtLapseShift",
408 Schedule -> {"IN " <> thorn <> "_convertToADMBaseGroup"},
409 ConditionalOnKeyword -> {"dt_lapse_shift_method", "correct"},
410 Where -> Interior,
411 Shorthands -> {dir[ua], detgt, gtu[ua,ub], eta, theta},
412 Equations ->
413 {
414 dir[ua] -> Sign[beta[ua]],
415
416 detgt -> 1 (* detgtExpr *),
417 (* This leads to simpler code... *)
418 gtu[ua,ub] -> 1/detgt detgtExpr MatrixInverse [gt[ua,ub]],
419
420 eta -> etaExpr,
421 theta -> thetaExpr,
422
423 (* see RHS *)
424 (*
425 admdtalpha -> - harmonicF alpha^harmonicN
426 ((1 - LapseAdvectionCoeff) A + LapseAdvectionCoeff trK)
427 + LapseAdvectionCoeff beta[ua] PDu[alpha,la],
428 *)
429 admdtalpha -> - harmonicF alpha^harmonicN
430 (+ LapseACoeff A
431 + ((1 - LapseACoeff)
432 (trK - IfCCZ4[2 Theta, 0])))
433 + LapseAdvectionCoeff Upwind[beta[ua], alpha, la],
434 admdtbeta[ua] -> IfThen[harmonicShift,
435 - 1/2 gtu[ua,uj] phi alpha
436 (- 2 alpha PD[phi,lj]
437 + 2 phi PD[alpha,lj]
438 + gtu[uk,ul] phi alpha
439 (PD[gt[lk,ll],lj] - 2 PD[gt[lj,lk],ll])),
440 (* else *)
441 + theta ShiftGammaCoeff
442 (+ ShiftBCoeff B[ua]
443 + (1 - ShiftBCoeff)
444 (Xt[ua] - eta BetaDriver beta[ua]))]
445 + ShiftAdvectionCoeff Upwind[beta[ub], beta[ua], lb]
446 }
447 };
448
449 convertToADMBaseDtLapseShiftBoundaryCalc =
450 {
451 Name -> thorn <> "_convertToADMBaseDtLapseShiftBoundary",
452 Schedule -> {"IN " <> thorn <> "_convertToADMBaseGroup"},
453 ConditionalOnKeyword -> {"dt_lapse_shift_method", "correct"},
454 Where -> BoundaryWithGhosts,
455 Shorthands -> {detgt, gtu[ua,ub], eta, theta},
456 Equations ->
457 {
458 detgt -> 1 (* detgtExpr *),
459 (* This leads to simpler code... *)
460 gtu[ua,ub] -> 1/detgt detgtExpr MatrixInverse [gt[ua,ub]],
461
462 eta -> etaExpr,
463 theta -> thetaExpr,
464
465 (* see RHS, but omit derivatives near the boundary *)
466 (*
467 admdtalpha -> - harmonicF alpha^harmonicN
468 ((1 - LapseAdvectionCoeff) A + LapseAdvectionCoeff trK),
469 *)
470 admdtalpha -> - harmonicF alpha^harmonicN
471 (+ LapseACoeff A
472 + ((1 - LapseACoeff)
473 (trK - IfCCZ4[2 Theta, 0]))),
474 admdtbeta[ua] -> IfThen[harmonicShift,
475 0,
476 (* else *)
477 + theta ShiftGammaCoeff
478 (+ ShiftBCoeff B[ua]
479 + (1 - ShiftBCoeff)
480 (Xt[ua] - eta BetaDriver beta[ua]))]
481 }
482 };
483
484 convertToADMBaseFakeDtLapseShiftCalc =
485 {
486 Name -> thorn <> "_convertToADMBaseFakeDtLapseShift",
487 Schedule -> {"IN " <> thorn <> "_convertToADMBaseGroup"},
488 ConditionalOnKeyword -> {"dt_lapse_shift_method", "noLapseShiftAdvection"},
489 Where -> Everywhere,
490 Shorthands -> {detgt, gtu[ua,ub], eta, theta},
491 Equations ->
492 {
493 detgt -> 1 (* detgtExpr *),
494 (* This leads to simpler code... *)
495 gtu[ua,ub] -> 1/detgt detgtExpr MatrixInverse [gt[ua,ub]],
496
497 eta -> etaExpr,
498 theta -> thetaExpr,
499
500 (* see RHS, but omit derivatives everywhere (which is wrong, but
501 faster, since it does not require synchronisation or boundary
502 conditions) *)
503 (*
504 admdtalpha -> - harmonicF alpha^harmonicN
505 ((1 - LapseAdvectionCoeff) A + LapseAdvectionCoeff trK),
506 *)
507 admdtalpha -> - harmonicF alpha^harmonicN
508 (+ LapseACoeff A
509 + ((1 - LapseACoeff)
510 (trK - IfCCZ4[2 Theta, 0]))),
511 admdtbeta[ua] -> IfThen[harmonicShift,
512 0,
513 (* else *)
514 + theta ShiftGammaCoeff
515 (+ ShiftBCoeff B[ua]
516 + (1 - ShiftBCoeff)
517 (Xt[ua] - eta BetaDriver beta[ua]))]
518 }
519 };
520
521 (******************************************************************************)
522 (* Evolution equations *)
523 (******************************************************************************)
524
525 evolCalc =
526 {
527 Name -> thorn <> "_RHS",
528 Schedule -> {"IN " <> thorn <> "_evolCalcGroup"},
529 (*
530 Where -> Interior,
531 *)
532 (* Synchronise the RHS grid functions after this routine, so that
533 the refinement boundaries are set correctly before applying the
534 radiative boundary conditions. *)
535 Where -> InteriorNoSync,
536 ConditionalOnKeyword -> {"RHS_split", "combined"},
537 Shorthands -> {dir[ua],
538 detgt, gtu[ua,ub],
539 Gt[ua,lb,lc], Gtl[la,lb,lc], Gtlu[la,lb,uc], Xtn[ua],
540 Rt[la,lb], Rphi[la,lb], R[la,lb],
541 Atm[ua,lb], Atu[ua,ub],
542 e4phi, em4phi, cdphi[la], cdphi2[la,lb], g[la,lb], detg,
543 gu[ua,ub], Ats[la,lb], trAts, eta, theta,
544 rho, S[la], trS, fac1, fac2, dottrK, dotXt[ua],
545 epsdiss[ua], IfCCZ4[Z[ua]], IfCCZ4[dotTheta]},
546 Equations ->
547 {
548 dir[ua] -> Sign[beta[ua]],
549
550 detgt -> 1 (* detgtExpr *),
551
552 (* This leads to simpler code... *)
553 gtu[ua,ub] -> 1/detgt detgtExpr MatrixInverse [gt[ua,ub]],
554 Gtl[la,lb,lc] -> 1/2
555 (PD[gt[lb,la],lc] + PD[gt[lc,la],lb] - PD[gt[lb,lc],la]),
556 Gtlu[la,lb,uc] -> gtu[uc,ud] Gtl[la,lb,ld],
557 Gt[ua,lb,lc] -> gtu[ua,ud] Gtl[ld,lb,lc],
558
559 (* The conformal connection functions calculated from the conformal metric,
560 used instead of Xt where no derivatives of Xt are taken *)
561 Xtn[ui] -> gtu[uj,uk] Gt[ui,lj,lk],
562
563 e4phi -> IfThen[conformalMethod==CMW, 1/phi^2, Exp[4 phi]],
564 em4phi -> 1 / e4phi,
565 g[la,lb] -> e4phi gt[la,lb],
566 detg -> detgExpr,
567 gu[ua,ub] -> em4phi gtu[ua,ub],
568
569 (* The Z quantities *)
570 (* gr-qc:1106.2254 (2011), eqn. (23) *)
571 IfCCZ4[
572 Z[ud] -> (1/2) gu[ua,ud] (- PD[gt[la,lb],lc] gtu[ub,uc] + gt[la,lc] Xt[uc])
573 ],
574
575 (* PRD 62, 044034 (2000), eqn. (18) *)
576 (* Adding Z term by changing Xtn to Xt *)
577 Rt[li,lj] -> - (1/2) gtu[ul,um] PD[gt[li,lj],ll,lm]
578 + (1/2) gt[lk,li] PD[Xt[uk],lj]
579 + (1/2) gt[lk,lj] PD[Xt[uk],li]
580 + (1/2) Xtn[uk] Gtl[li,lj,lk]
581 + (1/2) Xtn[uk] Gtl[lj,li,lk]
582 + (+ Gt[uk,li,ll] Gtlu[lj,lk,ul]
583 + Gt[uk,lj,ll] Gtlu[li,lk,ul]
584 + Gt[uk,li,ll] Gtlu[lk,lj,ul]),
585
586 fac1 -> IfThen[conformalMethod==CMW, -1/(2 phi), 1],
587 cdphi[la] -> fac1 CDt[phi,la],
588 fac2 -> IfThen[conformalMethod==CMW, 1/(2 phi^2), 0],
589 cdphi2[la,lb] -> fac1 CDt[phi,la,lb] + fac2 CDt[phi,la] CDt[phi,lb],
590
591 (* PRD 62, 044034 (2000), eqn. (15) *)
592 Rphi[li,lj] -> - 2 cdphi2[lj,li]
593 - 2 gt[li,lj] gtu[ul,un] cdphi2[ll,ln]
594 + 4 cdphi[li] cdphi[lj]
595 - 4 gt[li,lj] gtu[ul,un] cdphi[ln] cdphi[ll],
596
597 Atm[ua,lb] -> gtu[ua,uc] At[lc,lb],
598 Atu[ua,ub] -> Atm[ua,lc] gtu[ub,uc],
599
600 R[la,lb] -> Rt[la,lb] + Rphi[la,lb],
601 IfCCZ4[
602 R[la,lb] -> R[la,lb] + (2/phi) (+ g[la,lc] Z[uc] PD[phi,lb]
603 + g[lb,lc] Z[uc] PD[phi,la] - g[la,lb] Z[uc] PD[phi,lc])
604 + e4phi Z[uc] PD[gt[la,lb],lc]
605 ],
606
607 (* Matter terms *)
608
609 (* rho = n^a n^b T_ab *)
610 rho -> addMatter
611 (1/alpha^2 (T00 - 2 beta[ui] T0[li] + beta[ui] beta[uj] T[li,lj])),
612
613 (* S_i = -p^a_i n^b T_ab, where p^a_i = delta^a_i + n^a n_i *)
614 S[li] -> addMatter (-1/alpha (T0[li] - beta[uj] T[li,lj])),
615
616 (* trS = gamma^ij T_ij *)
617 trS -> addMatter (em4phi gtu[ui,uj] T[li,lj]),
618
619 (* RHS terms *)
620
621 (* PRD 62, 044034 (2000), eqn. (10) *)
622 (* PRD 67 084023 (2003), eqn. (16) and (23) *)
623 dot[phi] -> IfThen[conformalMethod==CMW, 1/3 phi, -1/6]
624 (alpha trK - PD[beta[ua],la]),
625
626 (* PRD 62, 044034 (2000), eqn. (9) *)
627 (* gr-qc:1106.2254 (2011), eqn. (14) *)
628 (* removing trA from Aij ensures that detg = 1 *)
629 dot[gt[la,lb]] -> - 2 alpha (At[la,lb] - IfCCZ4[(1/3) At[lc,ld] gtu[uc,ud] gt[la,lb], 0])
630 + gt[la,lc] PD[beta[uc],lb] + gt[lb,lc] PD[beta[uc],la]
631 - (2/3) gt[la,lb] PD[beta[uc],lc],
632 (* PRD 62, 044034 (2000), eqn. (20) *)
633 (* PRD 67 084023 (2003), eqn (26) *)
634 (* gr-qc:1106.2254 (2011), eqn. (19) *)
635 (* Adding Z terms by changing Xtn to Xt,
636 also adding extra Z and Theta terms *)
637 dotXt[ui] -> - 2 Atu[ui,uj] PD[alpha,lj]
638 + 2 alpha (+ Gt[ui,lj,lk] Atu[uk,uj]
639 - (2/3) gtu[ui,uj] PD[trK,lj]
640 + 6 Atu[ui,uj] cdphi[lj])
641 + gtu[uj,ul] PD[beta[ui],lj,ll]
642 + (1/3) gtu[ui,uj] PD[beta[ul],lj,ll]
643 - Xtn[uj] PD[beta[ui],lj]
644 + (2/3) Xtn[ui] PD[beta[uj],lj]
645 + IfCCZ4[
646 + GammaShift 2 e4phi (- Z[uj] PD[beta[ui],lj]
647 + (2/3) Z[ui] PD[beta[uj],lj])
648 - (4/3) alpha e4phi Z[ui] trK
649 + 2 gtu[ui,uj] (+ alpha PD[Theta,lj]
650 - Theta PD[alpha,lj])
651 - 2 alpha e4phi dampk1 Z[ui],
652 0]
653 (* Equation (4.28) in Baumgarte & Shapiro (Phys. Rept. 376 (2003) 41-131) *)
654 + addMatter (- 16 Pi alpha gtu[ui,uj] S[lj]),
655 dot[Xt[ui]] -> dotXt[ui],
656
657 (* gr-qc:1106.2254 (2011), eqn. (18) *)
658 IfCCZ4[
659 dotTheta ->
660 - PD[alpha,la] Z[ua] - dampk1 (2 + dampk2) alpha Theta
661 + (1/2) alpha (gu[ua,ub] R[la,lb] - Atm[ua,lb] Atm[ub,la] + (2/3) trK^2 - 2 trK Theta)
662 + addMatter (- 8 Pi alpha rho)
663 ],
664
665 IfCCZ4[
666 dot[Theta] -> dotTheta
667 ],
668
669 (* PRD 62, 044034 (2000), eqn. (11) *)
670 (* gr-qc:1106.2254 (2011), eqn. (17) *)
671 (* Adding the RHS of Theta to K, because K_Z4 = K_BSSN + 2 Theta *)
672 (* Also adding the Z term, as it has to cancel with the one in Theta *)
673 dottrK -> - em4phi ( gtu[ua,ub] ( PD[alpha,la,lb]
674 + 2 cdphi[la] PD[alpha,lb] )
675 - Xtn[ua] PD[alpha,la] )
676 + alpha (Atm[ua,lb] Atm[ub,la] + (1/3) trK^2)
677 + IfCCZ4[
678 + 2 dotTheta + 2 PD[alpha,la] Z[ua]
679 + dampk1 (1 - dampk2) alpha Theta,
680 0]
681 (* Equation (4.21) in Baumgarte & Shapiro (Phys. Rept. 376 (2003) 41-131) *)
682 + addMatter (4 Pi alpha (rho + trS)),
683 dot[trK] -> dottrK,
684
685 (* PRD 62, 044034 (2000), eqn. (12) *)
686 (* TODO: Should we use the Hamiltonian constraint to make Rij tracefree? *)
687 (* gr-qc:1106.2254 (2011), eqn. (15) *)
688 (* Adding Z terms in the Ricci and Theta terms *)
689 Ats[la,lb] -> - CDt[alpha,la,lb] +
690 + 2 (PD[alpha,la] cdphi[lb] + PD[alpha,lb] cdphi[la] )
691 + alpha R[la,lb],
692 trAts -> gu[ua,ub] Ats[la,lb],
693 dot[At[la,lb]] -> + em4phi (+ Ats[la,lb] - (1/3) g[la,lb] trAts )
694 + alpha (+ ((trK - IfCCZ4[2 Theta, 0])
695 At[la,lb])
696 - 2 At[la,lc] Atm[uc,lb])
697 + At[la,lc] PD[beta[uc],lb] + At[lb,lc] PD[beta[uc],la]
698 - (2/3) At[la,lb] PD[beta[uc],lc]
699 (* Equation (4.23) in Baumgarte & Shapiro (Phys. Rept. 376 (2003) 41-131) *)
700 + addMatter (- em4phi alpha 8 Pi
701 (T[la,lb] - (1/3) g[la,lb] trS)),
702
703 (* dot[alpha] -> - harmonicF alpha^harmonicN trK, *)
704 (* dot[alpha] -> - harmonicF alpha^harmonicN A + Lie[alpha, beta], *)
705 (*
706 dot[alpha] -> - harmonicF alpha^harmonicN (
707 (1 - LapseAdvectionCoeff) A + LapseAdvectionCoeff trK)
708 + LapseAdvectionCoeff beta[ua] PDu[alpha,la],
709 dot[A] -> (1 - LapseAdvectionCoeff) (dottrK - AlphaDriver A),
710 *)
711 dot[alpha] -> - harmonicF alpha^harmonicN
712 (+ LapseACoeff A
713 + ((1 - LapseACoeff)
714 (+ trK - IfCCZ4[2 Theta, 0]
715 + AlphaDriver (alpha - 1)))),
716
717 dot[A] -> + (LapseACoeff
718 (+ dottrK - IfCCZ4[2 dotTheta, 0]
719 - AlphaDriver A)),
720
721 eta -> etaExpr,
722 theta -> thetaExpr,
723
724 (* dot[beta[ua]] -> eta Xt[ua], *)
725 (* dot[beta[ua]] -> ShiftGammaCoeff alpha^ShiftAlphaPower B[ua], *)
726 dot[beta[ua]] -> IfThen[harmonicShift,
727 - 1/2 gtu[ua,uj] phi alpha
728 (- 2 alpha PD[phi,lj]
729 + 2 phi PD[alpha,lj]
730 + gtu[uk,ul] phi alpha
731 (PD[gt[lk,ll],lj] - 2 PD[gt[lj,lk],ll])),
732 (* else *)
733 + theta ShiftGammaCoeff
734 (+ ShiftBCoeff B[ua]
735 + (1 - ShiftBCoeff)
736 (Xt[ua] - eta BetaDriver beta[ua]))],
737
738 dot[B[ua]] -> + ShiftBCoeff (dotXt[ua] - eta BetaDriver B[ua])
739 (* Note that this dotXt[ua] is not yet \partial_t \tilde \Gamma^i, because the
740 advection term has not yet been added. It is actually
741 \partial_t \tilde \Gamma^i - \beta^j \partial_j \tilde \Gamma^i *)
742 }
743 };
744
745 advectCalc =
746 {
747 Name -> thorn <> "_Advect",
748 Schedule -> {"IN " <> thorn <> "_evolCalcGroup " <>
749 "AFTER (" <> thorn <> "_RHS " <> thorn <> "_RHS1 " <> thorn <> "_RHS2)"},
750 (*
751 Where -> Interior,
752 *)
753 (* Synchronise the RHS grid functions after this routine, so that
754 the refinement boundaries are set correctly before applying the
755 radiative boundary conditions. *)
756 Where -> InteriorNoSync,
757 ConditionalOnKeyword -> {"advection_split", "combined"},
758 Shorthands -> {dir[ua]},
759 Equations ->
760 {
761 dir[ua] -> Sign[beta[ua]],
762
763 dot[phi] -> dot[phi] + Upwind[beta[ua], phi, la],
764
765 dot[gt[la,lb]] -> dot[gt[la,lb]] + Upwind[beta[uc], gt[la,lb], lc],
766
767 dot[Xt[ui]] -> dot[Xt[ui]] + Upwind[beta[uj], Xt[ui], lj],
768
769 IfCCZ4[
770 dot[Theta] -> dot[Theta] + Upwind[beta[ua], Theta, la]
771 ],
772
773 dot[trK] -> dot[trK] + Upwind[beta[ua], trK, la],
774
775 dot[At[la,lb]] -> dot[At[la,lb]] + Upwind[beta[uc], At[la,lb], lc],
776
777 dot[alpha] -> dot[alpha]
778 + LapseAdvectionCoeff Upwind[beta[ua], alpha, la],
779
780 dot[A] -> dot[A]
781 + LapseACoeff (
782 + LapseAdvectionCoeff Upwind[beta[ua], A, la]
783 + (1 - LapseAdvectionCoeff) Upwind[beta[ua], trK, la]),
784
785 dot[beta[ua]] -> dot[beta[ua]]
786 + ShiftAdvectionCoeff Upwind[beta[ub], beta[ua], lb],
787
788 dot[B[ua]] -> dot[B[ua]]
789 + ShiftBCoeff (
790 + ShiftAdvectionCoeff Upwind[beta[ub], B[ua], lb]
791 + ((1 - ShiftAdvectionCoeff)
792 Upwind[beta[ub], Xt[ua], lb]))
793 (* Note that the advection term \beta^j \partial_j \tilde \Gamma^i is not
794 subtracted here when ShiftAdvectionCoefficient == 1 because it was
795 implicitly subtracted before (see comment in previous calculation of
796 dot[B[ua]]. *)
797 }
798 };
799
800 varsNames = {
801 {"phi", dot[phi]},
802 {"gt", dot[gt[la,lb]]},
803 {"Xt", dot[Xt[ui]]},
804 {"trK", dot[trK]},
805 {"At", dot[At[la,lb]]},
806 {"alpha", dot[alpha]},
807 {"A", dot[A]},
808 {"beta", dot[beta[ua]]},
809 {"B", dot[B[ua]]},
810 IfCCZ4[{"Theta", dot[Theta]}]
811 };
812
813 advectCalcs = Map[
814 PartialCalculation[advectCalc, "_"<>ToString[First[#]],
815 {ConditionalOnKeyword -> {"advection_split",
816 "per variable"}},
817 {Last[#]}]&,
818 varsNames];
819
820 evolCalc1 = PartialCalculation[evolCalc, "1",
821 {
822 ConditionalOnKeyword -> {"RHS_split", "split At"}
823 },
824 {
825 dot[phi],
826 dot[gt[la,lb]],
827 dot[Xt[ui]],
828 dot[trK],
829 dot[alpha],
830 dot[A],
831 dot[beta[ua]],
832 dot[B[ua]],
833 IfCCZ4[dot[Theta]]
834 }];
835
836 evolCalc2 = PartialCalculation[evolCalc, "2",
837 {
838 ConditionalOnKeyword -> {"RHS_split", "split At"}
839 },
840 {
841 dot[At[la,lb]]
842 }];
843
844 dissCalc =
845 {
846 Name -> thorn <> "_Dissipation",
847 Schedule -> {"IN " <> thorn <> "_evolCalcGroup " <>
848 "AFTER (" <> thorn <> "_RHS1 " <> thorn <> "_RHS2)"},
849 ConditionalOnKeyword -> {"apply_dissipation", "always"},
850 Where -> InteriorNoSync,
851 Shorthands -> {epsdiss[ua]},
852 Equations ->
853 {
854 epsdiss[ua] -> EpsDiss,
855 Sequence@@Table[
856 dot[var] -> dot[var] + epsdiss[ux] PDdiss[var,lx],
857 {var, {phi, gt[la,lb], Xt[ui], IfCCZ4[Theta], trK, At[la,lb],
858 alpha, A, beta[ua], B[ua]}}]
859 }
860 };
861
862 dissCalcs =
863 Table[
864 {
865 Name -> thorn <> "_Dissipation_" <> ToString[var /. {Tensor[n_,__] -> n}],
866 Schedule -> {"IN " <> thorn <> "_evolCalcGroup " <>
867 "AFTER (" <> thorn <> "_RHS1 " <> thorn <> "_RHS2)"},
868 ConditionalOnKeyword -> {"apply_dissipation", "always"},
869 Where -> InteriorNoSync,
870 Shorthands -> {epsdiss[ua]},
871 Equations ->
872 {
873 epsdiss[ua] -> EpsDiss,
874 dot[var] -> dot[var] + epsdiss[ux] PDdiss[var,lx]
875 }
876 },
877 {var, {phi, gt[la,lb], Xt[ui], IfCCZ4[Theta], trK, At[la,lb],
878 alpha, A, beta[ua], B[ua]}}
879 ];
880
881 RHSStaticBoundaryCalc =
882 {
883 Name -> thorn <> "_RHSStaticBoundary",
884 Schedule -> {"IN MoL_CalcRHS"},
885 ConditionalOnKeyword -> {"my_rhs_boundary_condition", "static"},
886 Where -> Boundary,
887 Equations ->
888 {
889 dot[phi] -> 0,
890 dot[gt[la,lb]] -> 0,
891 dot[trK] -> 0,
892 dot[At[la,lb]] -> 0,
893 dot[Xt[ua]] -> 0,
894 dot[alpha] -> 0,
895 dot[A] -> 0,
896 dot[beta[ua]] -> 0,
897 dot[B[ua]] -> 0,
898 IfCCZ4[dot[Theta] -> 0]
899 }
900 };
901
902 (* Initialise the RHS variables in analysis in case they are going to
903 be output - the noninterior points cannot be filled, so we define
904 them to be zero *)
905 initRHSCalc =
906 {
907 Name -> thorn <> "_InitRHS",
908 Schedule -> {"AT analysis BEFORE " <> thorn <> "_evolCalcGroup"},
909 Where -> Everywhere,
910 Equations ->
911 {
912 dot[phi] -> 0,
913 dot[gt[la,lb]] -> 0,
914 dot[trK] -> 0,
915 dot[At[la,lb]] -> 0,
916 dot[Xt[ua]] -> 0,
917 dot[alpha] -> 0,
918 dot[A] -> 0,
919 dot[beta[ua]] -> 0,
920 dot[B[ua]] -> 0,
921 IfCCZ4[dot[Theta] -> 0]
922 }
923 };
924
925 RHSRadiativeBoundaryCalc =
926 {
927 Name -> thorn <> "_RHSRadiativeBoundary",
928 Schedule -> {"IN MoL_CalcRHS"},
929 ConditionalOnKeyword -> {"my_rhs_boundary_condition", "radiative"},
930 Where -> Boundary,
931 Shorthands -> {dir[ua],
932 detgt, gtu[ua,ub], em4phi, gu[ua,ub],
933 nn[la], nu[ua], nlen, nlen2, su[ua],
934 vg},
935 Equations ->
936 {
937 dir[ua] -> Sign[normal[ua]],
938
939 detgt -> 1 (* detgtExpr *),
940 gtu[ua,ub] -> 1/detgt detgtExpr MatrixInverse [gt[ua,ub]],
941 em4phi -> IfThen[conformalMethod==CMW, phi^2, Exp[-4 phi]],
942 gu[ua,ub] -> em4phi gtu[ua,ub],
943
944 nn[la] -> Euc[la,lb] normal[ub],
945 nu[ua] -> gu[ua,ub] nn[lb],
946 nlen2 -> nu[ua] nn[la],
947 nlen -> Sqrt[nlen2],
948 su[ua] -> nu[ua] / nlen,
949
950 vg -> Sqrt[harmonicF],
951
952 dot[phi] -> - vg su[uc] PDo[phi ,lc],
953 dot[gt[la,lb]] -> - su[uc] PDo[gt[la,lb],lc],
954 dot[trK] -> - vg su[uc] PDo[trK ,lc],
955 dot[At[la,lb]] -> - su[uc] PDo[At[la,lb],lc],
956 dot[Xt[ua]] -> - su[uc] PDo[Xt[ua] ,lc],
957 dot[alpha] -> - vg su[uc] PDo[alpha ,lc],
958 dot[A] -> - vg su[uc] PDo[A ,lc],
959 dot[beta[ua]] -> - su[uc] PDo[beta[ua] ,lc],
960 dot[B[ua]] -> - su[uc] PDo[B[ua] ,lc],
961 IfCCZ4[
962 dot[Theta] -> - vg su[uc] PDo[Theta ,lc]
963 ]
964 }
965 };
966
967 enforceCalc =
968 {
969 Name -> thorn <> "_enforce",
970 Schedule -> {"IN MoL_PostStepModify"},
971 Shorthands -> {detgt, gtu[ua,ub], trAt},
972 Equations ->
973 {
974 (* The following comment is still interesting, but is not correct
975 any more since it is now scheduled in MoL_PostStepModify instead:
976
977 Enforcing the constraints needs to be a projection, because it
978 is applied in MoL_PostStep and may thus be applied multiple
979 times, not only during time evolution. Therefore detgt has to
980 be calculated correctly, without assuming that det gt_ij = 1,
981 which is not always the case (since we don't enforce it). On
982 the other hand, this may not be so important... *)
983 detgt -> 1 (* detgtExpr *),
984 gtu[ua,ub] -> 1/detgt detgtExpr MatrixInverse [gt[ua,ub]],
985
986 trAt -> gtu[ua,ub] At[la,lb],
987
988 At[la,lb] -> At[la,lb] - (1/3) gt[la,lb] trAt,
989
990 alpha -> Max[alpha, MinimumLapse]
991 }
992 };
993
994 (******************************************************************************)
995 (* Boundary conditions *)
996 (******************************************************************************)
997
998 boundaryCalc =
999 {
1000 Name -> thorn <> "_boundary",
1001 Schedule -> {"IN MoL_PostStep"},
1002 ConditionalOnKeyword -> {"my_boundary_condition", "Minkowski"},
1003 Where -> BoundaryWithGhosts,
1004 Equations ->
1005 {
1006 phi -> IfThen[conformalMethod==CMW, 1, 0],
1007 gt[la,lb] -> KD[la,lb],
1008 trK -> 0,
1009 At[la,lb] -> 0,
1010 Xt[ua] -> 0,
1011 alpha -> 1,
1012 A -> 0,
1013 beta[ua] -> 0,
1014 B[ua] -> 0,
1015 IfCCZ4[Theta -> 0]
1016 }
1017 };
1018
1019 (******************************************************************************)
1020 (* Constraint equations *)
1021 (******************************************************************************)
1022
1023 constraintsCalc =
1024 {
1025 Name -> thorn <> "_constraints",
1026 Schedule -> Automatic,
1027 After -> "MoL_PostStep",
1028 Where -> Interior,
1029 Shorthands -> {detgt, ddetgt[la], gtu[ua,ub], Z[ua],
1030 Gt[ua,lb,lc], Gtl[la,lb,lc], Gtlu[la,lb,uc], Xtn[ua],
1031 e4phi, em4phi,
1032 g[la,lb], detg, gu[ua,ub], ddetg[la], G[ua,lb,lc],
1033 Rt[la,lb], Rphi[la,lb], R[la,lb], trR, Atm[ua,lb],
1034 gK[la,lb,lc], cdphi[la], cdphi2[la,lb],
1035 rho, S[la], fac1, fac2},
1036 Equations ->
1037 {
1038 detgt -> 1 (* detgtExpr *),
1039 ddetgt[la] -> 0 (* ddetgtExpr[la] *),
1040
1041 (* This leads to simpler code... *)
1042 gtu[ua,ub] -> 1/detgt detgtExpr MatrixInverse [gt[ua,ub]],
1043 Gtl[la,lb,lc] -> 1/2
1044 (PD[gt[lb,la],lc] + PD[gt[lc,la],lb] - PD[gt[lb,lc],la]),
1045 Gtlu[la,lb,uc] -> gtu[uc,ud] Gtl[la,lb,ld],
1046 Gt[ua,lb,lc] -> gtu[ua,ud] Gtl[ld,lb,lc],
1047
1048 (* The conformal connection functions calculated from the conformal metric,
1049 used instead of Xt where no derivatives of Xt are taken *)
1050 Xtn[ui] -> gtu[uj,uk] Gt[ui,lj,lk],
1051
1052 e4phi -> IfThen[conformalMethod==CMW, 1/phi^2, Exp[4 phi]],
1053 em4phi -> 1 / e4phi,
1054 g[la,lb] -> e4phi gt[la,lb],
1055 detg -> e4phi^3,
1056 gu[ua,ub] -> em4phi gtu[ua,ub],
1057
1058 (* The Z quantities *)
1059 IfCCZ4[
1060 Z[ud] -> (1/2) gu[ua,ud] (- PD[gt[la,lb],lc] gtu[ub,uc] + gt[la,lc] Xt[uc])
1061 ],
1062
1063 (* PRD 62, 044034 (2000), eqn. (18) *)
1064 Rt[li,lj] -> - (1/2) gtu[ul,um] PD[gt[li,lj],ll,lm]
1065 + (1/2) gt[lk,li] PD[Xt[uk],lj]
1066 + (1/2) gt[lk,lj] PD[Xt[uk],li]
1067 + (1/2) Xtn[uk] Gtl[li,lj,lk]
1068 + (1/2) Xtn[uk] Gtl[lj,li,lk]
1069 + (+ Gt[uk,li,ll] Gtlu[lj,lk,ul]
1070 + Gt[uk,lj,ll] Gtlu[li,lk,ul]
1071 + Gt[uk,li,ll] Gtlu[lk,lj,ul]),
1072
1073 (* From the long turducken paper.
1074 This expression seems to give the same result as the one from 044034. *)
1075 (* TODO: symmetrise correctly: (ij) = (1/2) [i+j] *)
1076 (*
1077 Rt[li,lj] -> - (1/2) gtu[uk,ul] PD[gt[li,lj],lk,ll]
1078 + gt[lk,li] PD[Xt[uk],lj] + gt[lk,lj] PD[Xt[uk],li]
1079 + gt[li,ln] Gt[un,lj,lk] gtu[um,ua] gtu[uk,ub] PD[gt[la,lb],lm]
1080 + gt[lj,ln] Gt[un,li,lk] gtu[um,ua] gtu[uk,ub] PD[gt[la,lb],lm]
1081 + gtu[ul,us] (+ 2 Gt[uk,ll,li] gt[lj,ln] Gt[un,lk,ls]
1082 + 2 Gt[uk,ll,lj] gt[li,ln] Gt[un,lk,ls]
1083 + Gt[uk,li,ls] gt[lk,ln] Gt[un,ll,lj]),
1084 *)
1085
1086 (* Below would be a straightforward calculation,
1087 without taking any Gamma^i into account.
1088 This expression gives a different answer! *)
1089 (*
1090 Rt[la,lb] -> + Gt[u1,l2,la] Gt[l1,lb,u2] - Gt[u1,la,lb] Gt[l1,l2,u2]
1091 + 1/2 gtu[u1,u2] (- PD[gt[l1,l2],la,lb] + PD[gt[l1,la],l2,lb]
1092 - PD[gt[la,lb],l1,l2] + PD[gt[l2,lb],l1,la]),
1093 *)
1094
1095 fac1 -> IfThen[conformalMethod==CMW, -1/(2 phi), 1],
1096 cdphi[la] -> fac1 CDt[phi,la],
1097 fac2 -> IfThen[conformalMethod==CMW, 1/(2 phi^2), 0],
1098 cdphi2[la,lb] -> fac1 CDt[phi,la,lb] + fac2 CDt[phi,la] CDt[phi,lb],
1099
1100 (* PRD 62, 044034 (2000), eqn. (15) *)
1101 Rphi[li,lj] -> - 2 cdphi2[lj,li]
1102 - 2 gt[li,lj] gtu[ul,un] cdphi2[ll,ln]
1103 + 4 cdphi[li] cdphi[lj]
1104 - 4 gt[li,lj] gtu[ul,un] cdphi[ln] cdphi[ll],
1105
1106 (* ddetg[la] -> PD[e4phi detg,la], *)
1107 ddetg[la] -> e4phi ddetgt[la] + 4 detgt e4phi PD[phi,la],
1108 (* TODO: check this equation, maybe simplify it by omitting ddetg *)
1109 G[ua,lb,lc] -> Gt[ua,lb,lc]
1110 + 1/(2 detg) (+ KD[ua,lb] ddetg[lc] + KD[ua,lc] ddetg[lb]
1111 - (1/3) g[lb,lc] gu[ua,ud] ddetg[ld]),
1112
1113 R[la,lb] -> + Rt[la,lb] + Rphi[la,lb],
1114
1115 IfCCZ4[
1116 R[la,lb] -> R[la, lb] + (2/phi) (+ g[la,lc] Z[uc] PD[phi,lb]
1117 + g[lb,lc] Z[uc] PD[phi,la] - g[la,lb] Z[uc] PD[phi,lc])
1118 + e4phi Z[uc] PD[gt[la,lb],lc]
1119 ],
1120
1121 trR -> gu[ua,ub] R[la,lb],
1122
1123 (* K[la,lb] -> e4phi At[la,lb] + (1/3) g[la,lb] trK, *)
1124 (* Km[ua,lb] -> gu[ua,uc] K[lc,lb], *)
1125 Atm[ua,lb] -> gtu[ua,uc] At[lc,lb],
1126
1127 (* Matter terms *)
1128
1129 (* rho = n^a n^b T_ab *)
1130 rho -> 1/alpha^2 (T00 - 2 beta[ui] T0[li] + beta[ui] beta[uj] T[li,lj]),
1131
1132 (* S_i = -p^a_i n^b T_ab, where p^a_i = delta^a_i + n^a n_i *)
1133 S[li] -> -1/alpha (T0[li] - beta[uj] T[li,lj]),
1134
1135 (* Constraints *)
1136
1137 (* H -> trR - Km[ua,lb] Km[ub,la] + trK^2, *)
1138 (* PRD 67, 084023 (2003), eqn. (19) *)
1139 H -> trR - Atm[ua,lb] Atm[ub,la] + (2/3) trK^2 - addMatter 16 Pi rho,
1140
1141 (* gK[la,lb,lc] -> CD[K[la,lb],lc], *)
1142 (* gK[la,lb,lc] -> + 4 e4phi PD[phi,lc] At[la,lb] + e4phi CD[At[la,lb],lc]
1143 + (1/3) g[la,lb] PD[trK,lc],
1144 M[la] -> gu[ub,uc] (gK[lc,la,lb] - gK[lc,lb,la]), *)
1145
1146 M[li] -> + gtu[uj,uk] (CDt[At[li,lj],lk] + 6 At[li,lj] cdphi[lk])
1147 - (2/3) PD[trK,li]
1148 - addMatter 8 Pi S[li],
1149 (* TODO: use PRD 67, 084023 (2003), eqn. (20) *)
1150
1151 (* det gamma-tilde *)
1152 cS -> Log[detgt],
1153
1154 (* Gamma constraint *)
1155 cXt[ua] -> gtu[ub,uc] Gt[ua,lb,lc] - Xt[ua],
1156
1157 (* trace A-tilde *)
1158 cA -> gtu[ua,ub] At[la,lb]
1159 }
1160 };
1161
1162 constraintsCalc1 = PartialCalculation[constraintsCalc, "1",
1163 {},
1164 {
1165 H
1166 }];
1167
1168 constraintsCalc2 = PartialCalculation[constraintsCalc, "2",
1169 {},
1170 {
1171 M[li],
1172 cS,
1173 cXt[ua],
1174 cA
1175 }];
1176
1177 (******************************************************************************)
1178 (* Implementations *)
1179 (******************************************************************************)
1180
1181 inheritedImplementations =
1182 Join[{"ADMBase"},
1183 If [addMatter!=0, {"TmunuBase"}, {}]];
1184
1185 (******************************************************************************)
1186 (* Parameters *)
1187 (******************************************************************************)
1188
1189 inheritedKeywordParameters = {};
1190
1191 extendedKeywordParameters =
1192 {
1193 {
1194 Name -> "ADMBase::evolution_method",
1195 AllowedValues -> {thorn}
1196 },
1197 {
1198 Name -> "ADMBase::lapse_evolution_method",
1199 AllowedValues -> {thorn}
1200 },
1201 {
1202 Name -> "ADMBase::shift_evolution_method",
1203 AllowedValues -> {thorn}
1204 },
1205 {
1206 Name -> "ADMBase::dtlapse_evolution_method",
1207 AllowedValues -> {thorn}
1208 },
1209 {
1210 Name -> "ADMBase::dtshift_evolution_method",
1211 AllowedValues -> {thorn}
1212 }
1213 };
1214
1215 keywordParameters =
1216 {
1217 {
1218 Name -> "my_initial_data",
1219 (* Visibility -> "restricted", *)
1220 (* Description -> "ddd", *)
1221 AllowedValues -> {"ADMBase", "Minkowski"},
1222 Default -> "ADMBase"
1223 },
1224 {
1225 Name -> "my_initial_boundary_condition",
1226 Visibility -> "restricted",
1227 (* Description -> "ddd", *)
1228 AllowedValues -> {"none"},
1229 Default -> "none"
1230 },
1231 {
1232 Name -> "my_rhs_boundary_condition",
1233 Visibility -> "restricted",
1234 (* Description -> "ddd", *)
1235 AllowedValues -> {"none", "static", "radiative"},
1236 Default -> "none"
1237 },
1238 {
1239 Name -> "my_boundary_condition",
1240 (* Visibility -> "restricted", *)
1241 (* Description -> "ddd", *)
1242 AllowedValues -> {"none", "Minkowski"},
1243 Default -> "none"
1244 },
1245 {
1246 Name -> "calculate_ADMBase_variables_at",
1247 Visibility -> "restricted",
1248 (* Description -> "ddd", *)
1249 AllowedValues -> {"MoL_PostStep", "CCTK_EVOL", "CCTK_ANALYSIS"},
1250 Default -> "MoL_PostStep"
1251 },
1252 {
1253 Name -> "UseSpatialBetaDriver_UNUSED",
1254 Visibility -> "restricted",
1255 (* Description -> "ddd", *)
1256 AllowedValues -> {"no", "yes"},
1257 Default -> "no"
1258 },
1259 {
1260 Name -> "dt_lapse_shift_method",
1261 Description -> "Treatment of ADMBase dtlapse and dtshift",
1262 AllowedValues -> {"correct",
1263 "noLapseShiftAdvection" (* omit lapse and shift advection terms (faster) *)
1264 },
1265 Default -> "correct"
1266 },
1267 {
1268 Name -> "apply_dissipation",
1269 Description -> "Whether to apply dissipation to the RHSs",
1270 AllowedValues -> {"always",
1271 "never" (* yes and no keyword values confuse Cactus, and Kranc
1272 doesn't support boolean parameters *)
1273 },
1274 Default -> "never"
1275 },
1276 {
1277 Name -> "RHS_split",
1278 Description -> "How to split RHS calculation",
1279 AllowedValues -> {"combined",
1280 "split At"},
1281 Default -> "split At"
1282 },
1283 {
1284 Name -> "advection_split",
1285 Description -> "How to split advection calculation",
1286 AllowedValues -> {"combined",
1287 "per variable"},
1288 Default -> "combined"
1289 }
1290 };
1291
1292 intParameters =
1293 {
1294 {
1295 Name -> harmonicN,
1296 Description -> "d/dt alpha = - f alpha^n K (harmonic=2, 1+log=1)",
1297 Default -> 2
1298 },
1299 {
1300 Name -> ShiftAlphaPower,
1301 Default -> 0
1302 },
1303 {
1304 Name -> conformalMethod,
1305 Description -> "Treatment of conformal factor",
1306 AllowedValues -> {{Value -> "0", Description -> "phi method"},
1307 {Value -> "1", Description -> "W method"}},
1308 Default -> 0
1309 },
1310 {
1311 Name -> fdOrder,
1312 Default -> derivOrder,
1313 AllowedValues -> {2,4,6,8}
1314 },
1315 {
1316 Name -> harmonicShift,
1317 Description -> "Whether to use the harmonic shift",
1318 AllowedValues -> {{Value -> "0", Description -> "Gamma driver shift"},
1319 {Value -> "1", Description -> "Harmonic shift"}},
1320 Default -> 0
1321 }
1322 };
1323
1324 realParameters =
1325 {
1326 IfCCZ4[{
1327 Name -> GammaShift,
1328 Description -> "Covariant shift term in Gamma",
1329 Default -> 0.5
1330 }],
1331 IfCCZ4[{
1332 Name -> dampk1,
1333 Description -> "CCZ4 damping term 1 for Theta and Z",
1334 Default -> 0
1335 }],
1336 IfCCZ4[{
1337 Name -> dampk2,
1338 Description -> "CCZ4 damping term 2 for Theta and Z",
1339 Default -> 0
1340 }],
1341 {
1342 Name -> LapseACoeff,
1343 Description -> "Whether to evolve A in time",
1344 Default -> 0
1345 },
1346 {
1347 Name -> harmonicF,
1348 Description -> "d/dt alpha = - f alpha^n K (harmonic=1, 1+log=2)",
1349 Default -> 1
1350 },
1351 {
1352 Name -> AlphaDriver,
1353 Default -> 0
1354 },
1355 {
1356 Name -> ShiftBCoeff,
1357 Description -> "Whether to evolve B^i in time",
1358 Default -> 1
1359 },
1360 {
1361 Name -> ShiftGammaCoeff,
1362 Default -> 0
1363 },
1364 {
1365 Name -> BetaDriver,
1366 Default -> 0
1367 },
1368 {
1369 Name -> LapseAdvectionCoeff,
1370 Description -> "Factor in front of the lapse advection terms in 1+log",
1371 Default -> 1
1372 },
1373 {
1374 Name -> ShiftAdvectionCoeff,
1375 Description -> "Factor in front of the shift advection terms in gamma driver",
1376 Default -> 1
1377 },
1378 {
1379 Name -> MinimumLapse,
1380 Description -> "Minimum value of the lapse function",
1381 Default -> -1
1382 },
1383 {
1384 Name -> SpatialBetaDriverRadius,
1385 Description -> "Radius at which the BetaDriver starts to be reduced",
1386 AllowedValues -> {{Value -> "(0:*", Description -> "Positive"}},
1387 Default -> 10^12
1388 },
1389 {
1390 Name -> SpatialShiftGammaCoeffRadius,
1391 Description -> "Radius at which the ShiftGammaCoefficient starts to be reduced",
1392 AllowedValues -> {{Value -> "(0:*", Description -> "Positive"}},
1393 Default -> 10^12
1394 },
1395 {
1396 Name -> EpsDiss,
1397 Description -> "Dissipation strength",
1398 AllowedValues -> {{Value -> "(0:*", Description -> "Positive"}},
1399 Default -> 0
1400 }
1401 };
1402
1403 (******************************************************************************)
1404 (* Construct the thorns *)
1405 (******************************************************************************)
1406
1407 calculations =
1408 Join[
1409 {
1410 initialCalc,
1411 convertFromADMBaseCalc,
1412 initGammaCalc,
1413 convertFromADMBaseGammaCalc,
1414 evolCalc,
1415 evolCalc1, evolCalc2,
1416 dissCalc,
1417 advectCalc,
1418 (*advectCalcs,*)
1419 initRHSCalc,
1420 RHSStaticBoundaryCalc,
1421 (* RHSRadiativeBoundaryCalc, *)
1422 enforceCalc,
1423 boundaryCalc,
1424 convertToADMBaseCalc,
1425 convertToADMBaseDtLapseShiftCalc,
1426 convertToADMBaseDtLapseShiftBoundaryCalc,
1427 convertToADMBaseFakeDtLapseShiftCalc,
1428 (* constraintsCalc, *)
1429 constraintsCalc1, constraintsCalc2
1430 },
1431 advectCalcs
1432 (*dissCalcs*)
1433 ];
1434
1435 CreateKrancThornTT [groups, ".", thorn,
1436 Calculations -> calculations,
1437 DeclaredGroups -> declaredGroupNames,
1438 PartialDerivatives -> derivatives,
1439 EvolutionTimelevels -> evolutionTimelevels,
1440 DefaultEvolutionTimelevels -> 3,
1441 UseJacobian -> True,
1442 UseLoopControl -> True,
1443 UseVectors -> useVectors,
1444 UseOpenCL -> useOpenCL,
1445 InheritedImplementations -> inheritedImplementations,
1446 InheritedKeywordParameters -> inheritedKeywordParameters,
1447 ExtendedKeywordParameters -> extendedKeywordParameters,
1448 KeywordParameters -> keywordParameters,
1449 IntParameters -> intParameters,
1450 RealParameters -> realParameters
1451 ];
1452
1453 ];
1454
1455
1456
1457 (******************************************************************************)
1458 (* Options *)
1459 (******************************************************************************)
1460
1461 (* These are the arguments to createComment:
1462 - derivative order: 2, 4, 6, 8, ...
1463 - useJacobian: False or True
1464 - split upwind derivatives: False or True
1465 - use vectorisation: False or True
1466 - use OpenCL: False or True
1467 - timelevels: 2 or 3
1468 ## (keep this at 3; this is better chosen with a run-time parameter)
1469 - matter: 0 or 1
1470 ## (matter seems cheap; it should be always enabled)
1471 - thorn base name
1472 *)
1473
1474 createCode[4, False, True, True , False, 3, 1, "BSSN"];
1475 createCode[4, False, True, False, False, 3, 1, "BSSN"];
1476 createCode[4, False, True, True , True , 3, 1, "BSSN"];
1477
1478 createCode[4, False, True, True , False, 3, 1, "CCZ4"];
1479
33 ## 3-clause BSD license appended to this file.
44
55 function varargout = toledolu(LU)
6 ## -*- texinfo -*-
6 ## (*- texinfo -*)
77 ## @deftypefn{Function File} {[@var{L}, @var{U}, @var{P}]} = toledolu(@var{A})
88 ## @deftypefnx{Function File} {[@var{L}, @var{U}]} = toledolu(@var{A})
99 ## @deftypefnx{Function File} {@var{LUP}} = toledolu(@var{A})
1919 ## See the help for lu for details about the other calling forms.
2020 ##
2121 ## For the algorithm, see
22 ## @itemize
23 ## @item
22 ## (* @itemize *)
23 ## (* @item *)
2424 ## Toledo, Sivan. "Locality of reference in LU decomposition with
2525 ## partial pivoting," SIAM J. of Matrix Analysis and Applications,
2626 ## v18, n4, 1997. DOI: 10.1137/S0895479896297744
109109 end;
110110
111111 end.
112
113 class function Test.Run: Boolean;
114
115 #include <test.rh>
+0
-66
test/src_dir/perl.cgi less more
0 #!/usr/bin/perl -w
1
2 # ajaxCheckbox.pl - a script to test Ajax functionality
3
4 use strict;
5 use CGI qw/:standard/;
6 use CGI::Ajax;
7 use DBI;
8
9 # --- database authenication
10 my $dbh = do 'db.inc';
11
12 my $query = q{ SELECT project.project_id, project.name, project.phase, prio.prio,
13 HEX((255 - prio.prio)) AS hex, begun, tags
14 FROM project JOIN prio
15 ON (project.project_id = prio.project_id)
16 WHERE completed < 1
17 ORDER BY prio.prio DESC LIMIT 3};
18
19 my $sth = $dbh->prepare($query);
20 $sth->execute();
21 my $result = $dbh->selectall_arrayref($sth);
22
23 my $cgi = new CGI;
24 my $pjx = new CGI::Ajax( 'toStruck' => \&perl_func );
25 print $pjx->build_html( $cgi, \&Show_HTML);
26
27 sub Show_HTML {
28
29 use CGI qw/:standard/;
30
31 my $html = <<HEAD;
32 <!DOCTYPE html
33 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
34 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
35 <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
36 <head>
37 <title>This is the lastest source version</title>
38 <link rel="stylesheet" type="text/css" href="/css/carrot.css" />
39 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
40 </head><body>
41 <h2>Carrot Queue</h2><a href="/cgi-bin/source_carrot/index.cgi">Priority List</a><b>&nbsp; | &nbsp;</b>
42 <a href="/cgi-bin/source_carrot/add.cgi">Add a listing</a><b>&nbsp; | &nbsp;</b><div class="content" /><h4>Project listing</h4>
43 HEAD
44
45 foreach my $row (@$result) {
46 $html .= "<input type=\"checkbox\" name=name" . @$row[0] . " id=val" . @$row[0] . " value=\"ON\" onClick=\"toStruck( ['val@$row[0]'], ['div@$row[0]'] );\">";
47 $html .= "<div id=\"div@$row[0]\" style=\"display: inline;\"><!-- This gets entirely replaced -->" . @$row[1] . "</span></div><br>";
48 }
49
50 # you can append stuff to the HTML this way
51 $html .= "</body></html>";
52
53 return $html;
54 }
55
56 sub perl_func {
57 my $input=shift;
58
59 # if onClick the change the style
60 if ($input eq "ON") {
61 $input="<span style=\"text-decoration: line-through; display: inline;\">";
62 } else {
63 $input ="<span style=\"text-decoration: none; display: inline;\">";
64 }
65 }
0 /* test file for Prolog parsing */
1
2 % this is a Prolog source file
3
4 % select(Element, List, Remaining)
5
6 select(H, [H| T], T).
7 select(H, [X| R], [X| T]) :-
8 select(H, R, T).
0 class bob::open_ldap {
1
2 define foo::server (
3 $argsfile = undef,
4 $bdb_cachesize = '',
5 $bdb_checkpoint = '',
6 $bdb_directory = undef,
7 $bdb_idlcachesize = '',
8 $bdb_rootdn,
9 $bdb_rootpw,
10 $bdb_shm_key = '',
11 $bdb_suffix,
12 $conf_path = undef,
13 $conf_dir = undef,
14 $enable = false,
15 $include = [],
16 $includepath = undef,
17 $modulepath = '',
18 $modules = [],
19 $package = undef,
20 $pidfile = undef,
21 $sysconf_path = undef
22 ) {
23
24 $resource_name = "bob_openldap_server"
25
26 if($name != "params") {
27 fail("${resource_name}: This function is a singleton. Make sure the resource name is 'params'.")
28 }
29
30 case $operatingsystem {
31 Fedora: {
32 case $operatingsystemrelease {
33 /^(12|13)$/: {
34 if(!$argsfile) { $_argsfile = "/var/run/openldap/slapd.args" }
35 if(!$bdb_directory) { $_bdb_directory = "/var/lib/ldap" }
36 if(!$conf_path) { $_conf_path = "/etc/openldap/slapd.conf" }
37 if(!$conf_dir) { $_conf_dir = "/etc/openldap/slapd.d" }
38 if(!$package) { $_package = ["openldap-servers"] }
39 if(!$pidfile) { $_pidfile = "/var/run/openldap/slapd.pid" }
40 if(!$service) { $_service = "slapd" }
41 if(!$sysconf_path) { $_sysconf_path = "/etc/sysconfig/ldap" }
42 }
43 }
44 }
45 }
46
47 # Presume the OS did not match and because these args are necessary, just
48 # bail with an error.
49 if(!($_argsfile and $_bdb_directory and $_pidfile and $_conf_path and
50 $_package and $_service and $_sysconf_path and $_conf_dir)) {
51 fail("${resource_name}: Unsupported operating system: ${operatingsystem} version ${operatingsystemrelease} and you have not setup the args for: argsfile, bdb_directory, conf_dir, conf_path, package, pidfile, sysconf_path and service.")
52 }
53
54 # Fix paths - add forward slashes at the end of strings without them
55 $_includepath = regsubst($includepath, '([^/])$', '\1/')
56 $_dbconf_path = "${_bdb_directory}/DB_CONFIG"
57
58 # ...
59 file {
60 $_conf_path:
61 content => template("bob_openldap/slapd.conf"),
62 require => Package[$_package],
63 owner => "ldap",
64 group => "root",
65 mode => "0440",
66 notify => Service[$_service];
67 $_sysconf_path:
68 content => template("bob_openldap/ldap.sysconf"),
69 require => Package[$_package],
70 owner => "root",
71 group => "root",
72 mode => "0644";
73 $_conf_dir:
74 force => true,
75 ensure => absent,
76 before => Service[$_service];
77 $_dbconf_path:
78 content => "",
79 notify => Service[$_service];
80 }
81 package {
82 $_package:
83 ensure => installed;
84 }
85 service {
86 $_service:
87 ensure => $enable ? {
88 true => "running",
89 false => "stopped"
90 },
91 enable => $enable,
92 hasstatus => true,
93 require => [ Package[$_package], File[$_conf_path] ];
94 }
95 }
96
97 define client (
98 $base,
99 $network_timeout = '',
100 $path = undef,
101 $timeout = '',
102 $binddn = '',
103 $tls_cacertdir = undef,
104 $uri
105 ) {
106
107 $resource_name = "bob_openldap_client"
108
109 if($name != "params") {
110 fail("${resource_name}: This function is a singleton. Make sure the resource name is 'params'.")
111 }
112
113 case $operatingsystem {
114 Fedora: {
115 case $operatingsystemrelease {
116 /^(12|13)$/: {
117 if(!$tls_cacertdir) { $_tls_cacertdir = "/etc/openldap/cacerts" }
118 if(!$path) { $_path = "/etc/openldap/ldap.conf" }
119 }
120 }
121 }
122 }
123
124 # Presume the OS did not match and because these args are necessary, just
125 # bail with an error.
126 if(!($_tls_cacertdir and $_path)) {
127 fail("${resource_name}: Unsupported operating system: ${operatingsystem} version ${operatingsystemrelease} and you have not setup the args for: tls_cacertdir, path.")
128 }
129
130 # Fix some vars, ready for templating
131 $_base = $base
132 $_binddn = $binddn
133 $_network_timeout = $network_timeout
134 $_timeout = $timeout
135 $_uri = $uri
136
137 file {
138 $_path:
139 content => template("bob_openldap/ldap.conf")
140 }
141
142 }
143
144 }
0 class tester (
1 ) {
2 "Some Content"
3 }
0 class test::files {
1 "Some Content"
2 }
0 ;; =================================================
1 ;; Script: new-suffix.r
2 ;; downloaded from: www.REBOL.org
3 ;; on: 1-Jun-2011
4 ;; at: 21:19:08.38986 UTC
5 ;; owner: carl [script library member who can update
6 ;; this script]
7 ;; =================================================
8 REBOL [
9 Title: "Change File Extensions (Suffix)"
10 File: %new-suffix.r
11 Author: "Carl Sassenrath"
12 Date: 25-Jan-2005
13 Purpose: {
14 Change the file extension (suffix) for files with a specific extension.
15 For example, change all .txt files to .r files in the current directory.
16 Displays a list of changes before it makes them.
17 }
18 Warning: "Back up your files first, just in case!"
19 License: "BSD - Use at your own risk."
20 Library: [
21 level: 'beginner
22 platform: 'all
23 type: [tool]
24 domain: [files]
25 tested-under: none
26 support: none
27 license: 'bsd
28 see-also: none
29 ]
30 ]
31
32 from-suffix: %.txt
33 to-suffix: %.r
34
35 bulk-rename: func [confirmed] [
36 foreach file load %./ [
37 if all [
38 not find file #"/" ; (ignore directories)
39 from-suffix = find/last file #"."
40 ][
41 new-file: copy file
42 append clear find/last new-file #"." to-suffix
43 either confirmed [
44 print ["Renaming" file "to" new-file]
45 rename file new-file
46 ][
47 print ["Will rename" file "to" new-file]
48 ]
49 ]
50 ]
51 ]
52
53 bulk-rename false
54 if not confirm "Are you sure you want to rename all those files?" [
55 quit
56 ]
57 bulk-rename true
58 ask "Done. Press enter."
0 /*
1 * This is the example given by www.rust-lang.org
2 */
3 // Line comments work too
4 fn main() {
5 let nums = [1, 2];
6 let noms = ["Tim", "Eston", "Aaron", "Ben"];
7
8 let mut odds = nums.iter().map(|&x| x * 2 - 1);
9
10 for num in odds {
11 do spawn {
12 println!("{:s} says hello from a lightweight thread!", noms[num]);
13 }
14 }
15 }
0 (* Modula-3 *) INTERFACE M3Sample; (* file extension ".i3" *)
1
2 (* This is a comment *)
3
4 (* This is a comment ...
5 ... spanning more than one line *)
6
7 CONST
8 sqString = 'this is a string within "a string" ...\n';
9 dqString = "this is a string within 'a string' ...\n";
10
11 END M3Sample.
0 (* Modula-3 *) MODULE M3Sample; (* file extension ".m3" *)
1
2 (* This is a comment *)
3
4 (* This is a comment ...
5 ... spanning more than one line *)
6
7 CONST
8 sqString = 'this is a string within "a string" ...\n';
9 dqString = "this is a string within 'a string' ...\n";
10
11 END M3Sample.
0 MODULE Sample; (* in Modula-2 *)
1
2 (* This is a comment *)
3
4 (* This is a comment ...
5 ... spanning more than one line *)
6
7 CONST
8 sqString = 'this is a string within "a string" ...';
9 dqString = "this is a string within 'a string' ...";
10
11 END Sample.
0 (* Oberon-2 *) MODULE OberonSample; (* file extension ".ob2" *)
1
2 (* This is a comment *)
3
4 (* This is a comment ...
5 ... spanning more than one line *)
6
7 CONST
8 sqString* = 'this is a string within "a string" ...';
9 dqString* = "this is a string within 'a string' ...";
10
11 END OberonSample.
0 (* Oberon *) MODULE OberonSample; (* file extension ".obn" *)
1
2 (* This is a comment *)
3
4 (* This is a comment ...
5 ... spanning more than one line *)
6
7 CONST
8 sqString* = 'this is a string within "a string" ...';
9 dqString* = "this is a string within 'a string' ...";
10
11 END OberonSample.
0 DEFINITION MODULE Sample; (* in Modula-2 *)
1
2 (* This is a comment *)
3
4 (* This is a comment ...
5 ... spanning more than one line *)
6
7 CONST
8 sqString = 'this is a string within "a string" ...';
9 dqString = "this is a string within 'a string' ...";
10
11 END Sample.
0 IMPLEMENTATION MODULE Sample; (* in Modula-2 *)
1
2 (* This is a comment *)
3
4 (* This is a comment ...
5 ... spanning more than one line *)
6
7 CONST
8 sqString = 'this is a string within "a string" ...';
9 dqString = "this is a string within 'a string' ...";
10
11 END Sample.
0 var="\
1 Some string"
2
3 # Now a comment
4 var="some new string"
0 /*
1 * This is a TypeScript File
2 */
3
4 // And a regular comment
5
6 export class SomeClass {
7 public text: string;
8
9 public sayHello(name: string): string {
10 return `Hello, ${name}`;
11 }
12 }
0 // Do What The Fuck you Want to Public License 2 (WTFPL)
0 ../symlink_test_dir_target/
0 // c file
1 int function_a(void) {
2 int x;
3 }
11 // See COPYING for license information.
22
33 #include <assert.h>
4 #include <dirent.h>
45 #include <stdlib.h>
56 #include <string.h>
67
89 #include "../../src/languages.h"
910 #include "../../src/sourcefile.h"
1011
12 char **get_filenames(SourceFile *sourcefile) {
13 if (sourcefile->filenames == NULL) {
14 char dirpath[FILENAME_MAX];
15 strncpy(dirpath, sourcefile->filepath, sourcefile->dirpath);
16 dirpath[sourcefile->dirpath] = '\0';
17 struct dirent *file;
18 DIR *d = opendir((const char *)dirpath);
19 if (d) {
20 int length = 0;
21 while ((file = readdir(d))) length++;
22 closedir(d);
23
24 char **filenames = calloc(length + 1, sizeof(char *));
25 int i = 0;
26 d = opendir((const char *)dirpath);
27 while ((file = readdir(d))) {
28 int len = strlen(file->d_name);
29 char *filename = malloc(len + 1);
30 strncpy(filename, file->d_name, len);
31 filename[len] = '\0';
32 filenames[i++] = filename;
33 }
34 closedir(d);
35 sourcefile->filenames = filenames;
36 }
37 }
38 return sourcefile->filenames;
39 }
40
1141 #define ASSERT_DETECT(x, y) { \
1242 SourceFile *sf = ohcount_sourcefile_new("../detect_files/" y); \
43 get_filenames(sf); \
1344 const char *lang = ohcount_detect_language(sf); \
1445 assert(lang); \
1546 assert(strcmp(x, lang) == 0); \
1748 }
1849 #define ASSERT_NODETECT(x) { \
1950 SourceFile *sf = ohcount_sourcefile_new("../detect_files/" x); \
51 get_filenames(sf); \
2052 assert(ohcount_detect_language(sf) == NULL); \
2153 ohcount_sourcefile_free(sf); \
2254 }
2456 void test_detector_smalltalk() {
2557 ASSERT_DETECT(LANG_SMALLTALK, "example.st");
2658 ASSERT_NODETECT("english.st");
59 }
60
61 void test_detector_disambiguate_asx() {
62 ASSERT_DETECT(LANG_ASSEMBLER, "assembler6502.asx");
63 ASSERT_NODETECT("AdvancedStreamRedirector.asx");
64 }
65
66 void test_detector_disambiguate_def() {
67 ASSERT_DETECT(LANG_MODULA2, "sampleDef.def");
68 ASSERT_NODETECT("module-definition.def");
2769 }
2870
2971 void test_detector_disambiguate_m() {
3173 ASSERT_DETECT(LANG_OBJECTIVE_C, "t2.m");
3274 ASSERT_DETECT(LANG_OBJECTIVE_C, "TCPSocket.m");
3375 ASSERT_DETECT(LANG_OBJECTIVE_C, "foo_objective_c.m");
76 ASSERT_DETECT(LANG_MATHEMATICA, "foo_mathematica.m");
3477 ASSERT_DETECT(LANG_MATLAB, "foo_matlab.m");
3578 ASSERT_DETECT(LANG_OCTAVE, "foo_octave.m");
3679 }
3780
3881 void test_detector_disambiguate_in() {
3982 ASSERT_NODETECT("empty.in");
40 }
83 ASSERT_NODETECT("foo.in.in");
84 }
85
86 void test_detector_disambiguate_pl() {
87 ASSERT_DETECT(LANG_PERL, "foo_perl1.pl");
88 ASSERT_DETECT(LANG_PERL, "foo_perl2.pl");
89 ASSERT_DETECT(LANG_PROLOG, "foo_prolog1.pl");
90 ASSERT_DETECT(LANG_PERL, "perl_with_smiley.pl");
91 ASSERT_DETECT(LANG_PERL, "perl_shebang_prolog_body.pl");
92 }
93
4194 void test_detector_disambiguate_pro() {
4295 ASSERT_DETECT(LANG_IDL_PVWAVE, "foo.pro");
4396 ASSERT_DETECT(LANG_MAKE, "qmake.pro");
97 }
98
99 void test_detector_disambiguate_r() {
100 ASSERT_DETECT(LANG_R, "foo_r.R");
101 ASSERT_DETECT(LANG_REBOL, "foo_rebol_lower.r");
102 ASSERT_DETECT(LANG_REBOL, "foo_rebol_upper.r");
103 }
104
105 void test_detector_disambiguate_mod() {
106 ASSERT_DETECT(LANG_AMPL, "ampl.mod");
107 ASSERT_DETECT(LANG_MODULA2, "modula2.mod");
108 }
109
110 void test_detector_disambiguate_dat() {
111 ASSERT_DETECT(LANG_AMPL, "ampl.dat");
112 ASSERT_DETECT("\1", "binary.dat");
44113 }
45114
46115 void test_detector_fortran_fixedfree() {
56125 ASSERT_DETECT(LANG_CPP, "uses_cpp_keywords.h");
57126 ASSERT_DETECT(LANG_RUBY, "foo.rb");
58127 ASSERT_DETECT(LANG_MAKE, "foo.mk");
128 ASSERT_DETECT(LANG_MATHEMATICA, "foo.mt");
129 ASSERT_DETECT(LANG_MATHEMATICA, "foo.wl");
130 ASSERT_DETECT(LANG_MATHEMATICA, "foo.wlt");
59131 ASSERT_DETECT(LANG_OBJECTIVE_C, "foo_objective_c.h");
60132 ASSERT_DETECT(LANG_PHP, "upper_case_php");
61133 ASSERT_DETECT(LANG_SMALLTALK, "example.st");
62134 ASSERT_DETECT(LANG_VALA, "foo.vala");
135 ASSERT_DETECT(LANG_TEX_DTX, "foo.dtx");
63136 ASSERT_DETECT(LANG_TEX, "foo.tex");
137 ASSERT_DETECT(LANG_TYPESCRIPT, "foo.ts");
138 ASSERT_DETECT(LANG_TYPESCRIPT, "foo.tsx");
64139 ASSERT_DETECT(LANG_XSLT, "example.xsl");
140 ASSERT_DETECT(LANG_LOGTALK, "foo.lgt");
65141 ASSERT_DETECT(LANG_LISP, "core.lisp");
66142 ASSERT_DETECT(LANG_DMD, "foo.d");
67143 ASSERT_DETECT(LANG_VIM, "foo.vim");
144 ASSERT_DETECT(LANG_EC, "foo.ec");
145 ASSERT_DETECT(LANG_EC, "foo.eh");
68146 ASSERT_DETECT(LANG_EBUILD, "foo.ebuild");
69147 ASSERT_DETECT(LANG_EBUILD, "foo.eclass");
70148 ASSERT_DETECT(LANG_EXHERES, "foo.exheres-0");
71149 ASSERT_DETECT(LANG_EXHERES, "foo.exlib");
72150 ASSERT_DETECT(LANG_EIFFEL, "eiffel.e");
73151 ASSERT_DETECT(LANG_OCAML, "ocaml.ml");
152 ASSERT_DETECT(LANG_AUGEAS, "augeas.aug");
74153 ASSERT_DETECT(LANG_STRATEGO, "stratego.str");
75 ASSERT_DETECT(LANG_R, "foo.R");
76154 ASSERT_DETECT(LANG_GLSL, "foo.glsl");
77155 ASSERT_DETECT(LANG_GLSL, "foo_glsl.vert");
78156 ASSERT_DETECT(LANG_GLSL, "foo_glsl.frag");
79 ASSERT_DETECT(LANG_IDL_PVWAVE, "foo.pro");
157 ASSERT_DETECT(LANG_IDL_PVWAVE, "foo.pro");
80158 ASSERT_DETECT(LANG_ASSEMBLER, "foo.z80");
81159 ASSERT_DETECT(LANG_PHP, "php.inc");
160 ASSERT_DETECT(LANG_FORTH, "forth.4th");
161 ASSERT_DETECT(LANG_FORTH, "forth.fr");
162 ASSERT_DETECT(LANG_FSHARP, "fs1.fs");
163 ASSERT_DETECT(LANG_GRACE, "grace1.grace");
164 ASSERT_DETECT(LANG_GRACE, "grace2.grc");
165 ASSERT_DETECT(LANG_AUTOCONF, "m4.m4");
166 ASSERT_DETECT(LANG_NSIS, "foo.nsi");
167 ASSERT_DETECT(LANG_NSIS, "foo.nsh");
168 ASSERT_DETECT(LANG_COFFEESCRIPT, "foo.coffee");
169 ASSERT_DETECT(LANG_QML, "foo.qml");
170 ASSERT_DETECT(LANG_COQ, "coq.v");
171 ASSERT_DETECT(LANG_AMPL, "foo.run");
82172 ASSERT_NODETECT("empty.inc");
83 ASSERT_DETECT(LANG_FSHARP, "fs1.fs");
84173 }
85174
86175 void test_detector_upper_case_extensions() {
98187 ASSERT_DETECT(LANG_TCL, "tcl_script");
99188 ASSERT_DETECT(LANG_PYTHON, "python.data");
100189 ASSERT_DETECT(LANG_PYTHON, "python2.data");
190 ASSERT_DETECT(LANG_CPP, "uses_cpp_modeline");
101191 }
102192
103193 void test_detector_csharp_or_clearsilver() {
108198 void test_detector_basic() {
109199 ASSERT_DETECT(LANG_VISUALBASIC, "visual_basic.bas");
110200 ASSERT_DETECT(LANG_CLASSIC_BASIC, "classic_basic.b");
111 system("mv ../detect_files/frx1.frx ../detect_files/frx1.frx2");
201 assert(system("mv ../detect_files/frx1.frx ../detect_files/frx1.frx2") == 0);
112202 ASSERT_DETECT(LANG_STRUCTURED_BASIC, "visual_basic.bas");
113203 ASSERT_DETECT(LANG_STRUCTURED_BASIC, "structured_basic.b");
114 system("mv ../detect_files/frx1.frx2 ../detect_files/frx1.frx");
204 assert(system("mv ../detect_files/frx1.frx2 ../detect_files/frx1.frx") == 0);
115205 }
116206
117207 void test_detector_xml_with_custom_extension() {
118208 ASSERT_DETECT(LANG_XML, "xml.custom_ext");
119209 }
120210
211 void test_detector_brainfuck() {
212 ASSERT_DETECT(LANG_BRAINFUCK, "foo.bf");
213 ASSERT_DETECT(LANG_BFPP, "foo.bfpp");
214 }
215
216 void test_detector_emacs_mode() {
217 ASSERT_DETECT(LANG_C, "emacs_mode_c");
218 }
219
220 void test_detector_emacs_with_extension() {
221 ASSERT_DETECT(LANG_RUBY, "java_emac.rb");
222 ASSERT_DETECT(LANG_JAVASCRIPT, "javascript_emac.js");
223 }
224
225 void test_detector_puppet(){
226 ASSERT_DETECT(LANG_PUPPET, "puppet_import.pp");
227 ASSERT_DETECT(LANG_PUPPET, "puppet_test.pp");
228 }
229
230 void test_detector_genie(){
231 ASSERT_DETECT(LANG_GENIE, "client-osx.gs");
232 }
233
234 void test_detector_rust(){
235 ASSERT_DETECT(LANG_RUST, "rust.rs");
236 // When RenderScript is implemented, this will, of course, need to be removed.
237 ASSERT_NODETECT("renderscript.rs");
238 }
239
240 void test_detector_ampl(){
241 ASSERT_DETECT(LANG_AMPL, "foo.run");
242 }
243
244 void test_non_existent_file(){
245 ASSERT_NODETECT("xxx_non_exists_xxxi.pp");
246 }
247
121248 void all_detector_tests() {
122249 test_detector_smalltalk();
250 test_detector_disambiguate_asx();
251 test_detector_disambiguate_def();
123252 test_detector_disambiguate_m();
124253 test_detector_disambiguate_in();
254 test_detector_disambiguate_pl();
125255 test_detector_disambiguate_pro();
256 test_detector_disambiguate_r();
257 test_detector_disambiguate_mod();
258 test_detector_disambiguate_dat();
126259 test_detector_fortran_fixedfree();
127260 test_detector_detect_polyglot();
128261 test_detector_upper_case_extensions();
130263 test_detector_csharp_or_clearsilver();
131264 test_detector_basic();
132265 test_detector_xml_with_custom_extension();
133 }
266 test_detector_brainfuck();
267 test_detector_emacs_mode();
268 test_detector_emacs_with_extension();
269 test_detector_puppet();
270 test_detector_genie();
271 test_detector_rust();
272 test_detector_ampl();
273 test_non_existent_file();
274 }
3636 length = p - file->d_name;
3737 strncpy(e_p, (const char *)file->d_name, length);
3838 *(e_p + length) = '\0';
39 FILE *f = fopen((const char *)expected, "r");
39 FILE *f = fopen((const char *)expected, "rb");
4040 if (f) {
4141 SourceFile *sf = ohcount_sourcefile_new((const char *)src);
4242 LicenseList *iter = ohcount_sourcefile_get_license_list(sf)->head;
7474
7575 #include "parsers/test_actionscript.h"
7676 #include "parsers/test_ada.h"
77 #include "parsers/test_ampl.h"
7778 #include "parsers/test_assembler.h"
79 #include "parsers/test_augeas.h"
7880 #include "parsers/test_autoconf.h"
7981 #include "parsers/test_automake.h"
8082 #include "parsers/test_awk.h"
8284 #include "parsers/test_bat.h"
8385 #include "parsers/test_blitzmax.h"
8486 #include "parsers/test_boo.h"
87 #include "parsers/test_brainfuck.h"
88 #include "parsers/test_bfpp.h"
8589 #include "parsers/test_c.h"
90 #include "parsers/test_chaiscript.h"
8691 #include "parsers/test_clearsilvertemplate.h"
8792 #include "parsers/test_clearsilver.h"
93 #include "parsers/test_clojure.h"
94 #include "parsers/test_coq.h"
8895 #include "parsers/test_cs_aspx.h"
8996 #include "parsers/test_csharp.h"
9097 #include "parsers/test_css.h"
97104 #include "parsers/test_erlang.h"
98105 #include "parsers/test_exheres.h"
99106 #include "parsers/test_factor.h"
107 #include "parsers/test_forth.h"
100108 #include "parsers/test_fortran.h"
101109 #include "parsers/test_fsharp.h"
102110 #include "parsers/test_glsl.h"
111 #include "parsers/test_golang.h"
103112 #include "parsers/test_groovy.h"
104113 #include "parsers/test_haml.h"
105114 #include "parsers/test_haskell.h"
106115 #include "parsers/test_haxe.h"
107116 #include "parsers/test_html.h"
108117 #include "parsers/test_idl_pvwave.h"
118 #include "parsers/test_jam.h"
109119 #include "parsers/test_java.h"
110120 #include "parsers/test_javascript.h"
111121 #include "parsers/test_jsp.h"
112122 #include "parsers/test_lisp.h"
123 #include "parsers/test_logtalk.h"
113124 #include "parsers/test_lua.h"
114125 #include "parsers/test_make.h"
126 #include "parsers/test_mathematica.h"
115127 #include "parsers/test_matlab.h"
116128 #include "parsers/test_metafont.h"
117129 #include "parsers/test_metapost.h"
118130 #include "parsers/test_mxml.h"
119131 #include "parsers/test_nix.h"
132 #include "parsers/test_nsis.h"
120133 #include "parsers/test_objective_j.h"
121134 #include "parsers/test_ocaml.h"
122135 #include "parsers/test_octave.h"
123136 #include "parsers/test_pascal.h"
124137 #include "parsers/test_perl.h"
125138 #include "parsers/test_pike.h"
139 #include "parsers/test_puppet.h"
126140 #include "parsers/test_python.h"
141 #include "parsers/test_qml.h"
127142 #include "parsers/test_r.h"
143 #include "parsers/test_racket.h"
144 #include "parsers/test_rebol.h"
128145 #include "parsers/test_rexx.h"
129146 #include "parsers/test_rhtml.h"
130147 #include "parsers/test_ruby.h"
137154 #include "parsers/test_stratego.h"
138155 #include "parsers/test_tcl.h"
139156 #include "parsers/test_tex.h"
157 #include "parsers/test_typescript.h"
140158 #include "parsers/test_vala.h"
141159 #include "parsers/test_vb_aspx.h"
142160 #include "parsers/test_vhdl.h"
168186 end - start);
169187 line2[strlen(language) + strlen(entity) + 2 + (end - start)] = '\0';
170188 if (strcmp(line, line2) != 0) {
171 fprintf(stderr, "lines didn't match:\n1: '%s'\n2: '%s'\n", line, line2);
172 if (strcmp(line, line2) != 0) {
173 fprintf(stderr, "lines didn't match:\n1: '%s'\n2: '%s'\n", line, line2);
174 assert(strcmp(line, line2) == 0);
175 }
189 fprintf(stderr, "FAIL: Parser test failure in %s:\nExpected: %sGot: %s", udata->sf->filename, line, line2);
190 assert(strcmp(line, line2) == 0);
176191 }
177192 }
178193
201216 strncpy(e_p, (const char *)file->d_name, length);
202217 *(e_p + length) = '\0';
203218
204 FILE *f = fopen((const char *)expected, "r");
219 FILE *f = fopen((const char *)expected, "rb");
205220 if (f) {
206221 SourceFile *sf = ohcount_sourcefile_new((const char *)src);
207222
212227 if (strcmp(s_p, "visual_basic.bas") == 0)
213228 // This file needs frx1.frx in the directory contents to be
214229 // detected as Visual Basic.
215 ohcount_sourcefile_set_filenames(sf, test_basic_vb_filenames);
230 sf->filenames = test_basic_vb_filenames;
216231 else
217 ohcount_sourcefile_set_filenames(sf, test_parser_filenames);
232 sf->filenames = test_parser_filenames;
218233
219234 TestParserUData *udata = malloc(sizeof(TestParserUData));
220235 udata->sf = sf;
246261 test_parser_verify_parses();
247262 all_actionscript_tests();
248263 all_ada_tests();
264 all_ampl_tests();
249265 all_assembler_tests();
266 all_augeas_tests();
250267 all_autoconf_tests();
251268 all_automake_tests();
252269 all_awk_tests();
254271 all_bat_tests();
255272 all_blitzmax_tests();
256273 all_boo_tests();
274 all_brainfuck_tests();
275 all_bfpp_tests();
257276 all_c_tests();
277 all_chaiscript_tests();
258278 all_clearsilver_template_tests();
259279 all_clearsilver_tests();
280 all_clojure_tests();
281 all_coq_tests();
260282 all_cs_aspx_tests();
261283 all_csharp_tests();
262284 all_css_tests();
269291 all_erlang_tests();
270292 all_exheres_tests();
271293 all_factor_tests();
294 all_forth_tests();
272295 all_fortran_tests();
273296 all_fsharp_tests();
274297 all_glsl_tests();
278301 all_haxe_tests();
279302 all_html_tests();
280303 all_idl_pvwave_tests();
304 all_jam_tests();
281305 all_java_tests();
282306 all_javascript_tests();
283307 all_jsp_tests();
284308 all_lisp_tests();
309 all_logtalk_tests();
285310 all_lua_tests();
286311 all_make_tests();
312 all_mathematica_tests();
287313 all_matlab_tests();
288314 all_metafont_tests();
289315 all_metapost_tests();
290316 all_mxml_tests();
291317 all_nix_tests();
318 all_nsis_tests();
292319 all_objective_j_tests();
293320 all_ocaml_tests();
294321 all_octave_tests();
297324 all_pike_tests();
298325 all_python_tests();
299326 all_r_tests();
327 all_racket_tests();
328 all_rebol_tests();
300329 all_rexx_tests();
301330 all_rhtml_tests();
302331 all_ruby_tests();
0
1 void test_ampl_comments() {
2 test_parser_verify_parse(
3 test_parser_sourcefile("ampl", " #comment"),
4 "ampl", "", "#comment", 0
5 );
6 }
7
8 void test_ampl_comment_entities() {
9 test_parser_verify_entity(
10 test_parser_sourcefile("ampl", " #comment"),
11 "comment", "#comment"
12 );
13 }
14
15 void all_ampl_tests() {
16 test_ampl_comments();
17 test_ampl_comment_entities();
18 }
0
1 void test_augeas_comments() {
2 test_parser_verify_parse(
3 test_parser_sourcefile("augeas", " (* comment *)"),
4 "augeas", "", "(* comment *)", 0
5 );
6 }
7
8 void test_augeas_comment_entities() {
9 test_parser_verify_entity(
10 test_parser_sourcefile("augeas", " (*comment*)"),
11 "comment", "(*comment*)"
12 );
13 }
14
15 void all_augeas_tests() {
16 test_augeas_comments();
17 test_augeas_comment_entities();
18 }
0 void test_bfpp_comment() {
1 test_parser_verify_parse(
2 test_parser_sourcefile("bfpp", " = comment"),
3 "bfpp", "", "= comment", 0
4 );
5 }
6
7 void test_bfpp_comment_entities() {
8 test_parser_verify_entity(
9 test_parser_sourcefile("bfpp", " = comment"),
10 " comment", "= comment"
11 );
12 }
13
14 void all_bfpp_tests() {
15 test_bfpp_comment();
16 test_bfpp_comment_entities();
17 }
18
0 void test_brainfuck_comment() {
1 test_parser_verify_parse(
2 test_parser_sourcefile("brainfuck", " #comment"),
3 "brainfuck", "", "#comment", 0
4 );
5 }
6
7 void test_brainfuck_comment_entities() {
8 test_parser_verify_entity(
9 test_parser_sourcefile("brainfuck", " #comment"),
10 "#comment", "#comment"
11 );
12 }
13
14 void all_brainfuck_tests() {
15 test_brainfuck_comment();
16 test_brainfuck_comment_entities();
17 }
0
1 void test_chaiscript_comments() {
2 test_parser_verify_parse(
3 test_parser_sourcefile("chaiscript", " //comment"),
4 "chaiscript", "", "//comment", 0
5 );
6 }
7
8 void test_chaiscript_comment_entities() {
9 test_parser_verify_entity(
10 test_parser_sourcefile("chaiscript", " //comment"),
11 "comment", "//comment"
12 );
13 test_parser_verify_entity(
14 test_parser_sourcefile("chaiscript", " /*comment*/"),
15 "comment", "/*comment*/"
16 );
17 }
18
19 void all_chaiscript_tests() {
20 test_chaiscript_comments();
21 test_chaiscript_comment_entities();
22 }
0
1 void test_clojure_comments() {
2 test_parser_verify_parse(
3 test_parser_sourcefile("clojure", " ;;; comment"),
4 "clojure", "", ";;; comment", 0
5 );
6 }
7
8 void test_clojure_comment_entities() {
9 test_parser_verify_entity(
10 test_parser_sourcefile("clojure", " ;comment"),
11 "comment", ";comment"
12 );
13 }
14
15 void all_clojure_tests() {
16 test_clojure_comments();
17 test_clojure_comment_entities();
18 }
0
1 void test_coq_comments() {
2 test_parser_verify_parse(
3 test_parser_sourcefile("coq", " (* comment *)"),
4 "coq", "", "(* comment *)", 0
5 );
6 }
7
8 void test_coq_comment_entities() {
9 test_parser_verify_entity(
10 test_parser_sourcefile("coq", " (*comment*)"),
11 "comment", "(*comment*)"
12 );
13 }
14
15 void all_coq_tests() {
16 test_coq_comments();
17 test_coq_comment_entities();
18 }
0
1 void test_forth_comment_entities() {
2 test_parser_verify_entity(
3 test_parser_sourcefile("forth", " \\comment"),
4 "comment", "\\comment"
5 );
6 test_parser_verify_entity(
7 test_parser_sourcefile("forth", " (comment)"),
8 "comment", "(comment)"
9 );
10 }
11
12 void all_forth_tests() {
13 test_forth_comment_entities();
14 }
0
1 void test_golang_comments() {
2 test_parser_verify_parse(
3 test_parser_sourcefile("go", " //comment"),
4 "go", "", "//comment", 0
5 );
6 }
7
8 void test_golang_empty_comments() {
9 test_parser_verify_parse(
10 test_parser_sourcefile("go", " //\n"),
11 "go", "", "//\n", 0
12 );
13 }
14
15 void test_golang_block_comment() {
16 test_parser_verify_parse(
17 test_parser_sourcefile("go", "/*c*/"),
18 "go", "", "/*c*/", 0
19 );
20 }
21
22 void test_golang_comment_entities() {
23 test_parser_verify_entity(
24 test_parser_sourcefile("go", " //comment"),
25 "comment", "//comment"
26 );
27 test_parser_verify_entity(
28 test_parser_sourcefile("go", " /*comment*/"),
29 "comment", "/*comment*/"
30 );
31 }
32
33 void all_golang_tests() {
34 test_golang_comments();
35 test_golang_empty_comments();
36 test_golang_block_comment();
37 test_golang_comment_entities();
38 }
0
1 void test_jam_comments() {
2 test_parser_verify_parse(
3 test_parser_sourcefile("jam", " #comment"),
4 "jam", "", "#comment", 0
5 );
6 }
7
8 void test_jam_comment_entities() {
9 test_parser_verify_entity(
10 test_parser_sourcefile("jam", " #comment"),
11 "comment", "#comment"
12 );
13 }
14
15 void all_jam_tests() {
16 test_jam_comments();
17 test_jam_comment_entities();
18 }
0
1 void test_logtalk_comments() {
2 test_parser_verify_parse(
3 test_parser_sourcefile("logtalk", " %comment"),
4 "logtalk", "", "%comment", 0
5 );
6 }
7
8 void test_logtalk_empty_comments() {
9 test_parser_verify_parse(
10 test_parser_sourcefile("logtalk", " %\n"),
11 "logtalk", "", "%\n", 0
12 );
13 }
14
15 void test_logtalk_block_comment() {
16 test_parser_verify_parse(
17 test_parser_sourcefile("logtalk", " /*d*/"),
18 "logtalk", "", "/*d*/", 0
19 );
20 }
21
22 void all_logtalk_tests() {
23 test_logtalk_comments();
24 test_logtalk_empty_comments();
25 test_logtalk_block_comment();
26 }
0
1 void test_mathematica_comment_entities() {
2 test_parser_verify_entity(
3 test_parser_sourcefile("mathematica", " (*comment*)"),
4 "comment", "(*comment*)"
5 );
6 }
7
8 void all_mathematica_tests() {
9 test_mathematica_comment_entities();
10 }
0
1 void test_nsis_comments() {
2 test_parser_verify_parse(
3 test_parser_sourcefile("nsis", " ;comment"),
4 "nsis", "", ";comment", 0
5 );
6 test_parser_verify_parse(
7 test_parser_sourcefile("nsis", " #comment"),
8 "nsis", "", "#comment", 0
9 );
10 test_parser_verify_parse(
11 test_parser_sourcefile("nsis", " /*comment*/"),
12 "nsis", "", "/*comment*/", 0
13 );
14 }
15
16 void test_nsis_strings() {
17 test_parser_verify_parse(
18 test_parser_sourcefile("nsis", "\"abc;not a 'comment\""),
19 "nsis", "\"abc;not a 'comment\"", "", 0
20 );
21 test_parser_verify_parse(
22 test_parser_sourcefile("nsis", "'abc;not a \"comment'"),
23 "nsis", "'abc;not a \"comment'", "", 0
24 );
25 test_parser_verify_parse(
26 test_parser_sourcefile("nsis", "`abc;not a 'comment`"),
27 "nsis", "`abc;not a 'comment`", "", 0
28 );
29 }
30
31 void test_nsis_comment_entities() {
32 test_parser_verify_entity(
33 test_parser_sourcefile("nsis", " ;comment"),
34 "comment", ";comment"
35 );
36 test_parser_verify_entity(
37 test_parser_sourcefile("nsis", " #comment"),
38 "comment", "#comment"
39 );
40 test_parser_verify_entity(
41 test_parser_sourcefile("nsis", " /*comment*/"),
42 "comment", "/*comment*/"
43 );
44 }
45
46 void all_nsis_tests() {
47 test_nsis_comments();
48 test_nsis_strings();
49 test_nsis_comment_entities();
50 }
0
1 void test_puppet_comments() {
2 test_parser_verify_parse(
3 test_parser_sourcefile("puppet", " #comment"),
4 "puppet", "", "#comment", 0
5 );
6 }
7
8 void test_puppet_comment_entities() {
9 test_parser_verify_entity(
10 test_parser_sourcefile("puppet", " #comment"),
11 "comment", "#comment"
12 );
13 test_parser_verify_entity(
14 test_parser_sourcefile("puppet", " /*comment*/"),
15 "comment", "/*comment*/"
16 );
17 }
18
19 void all_puppet_tests() {
20 test_puppet_comments();
21 test_puppet_comment_entities();
22 }
0
1 void test_qml_comments() {
2 test_parser_verify_parse(
3 test_parser_sourcefile("qml", " //comment"),
4 "qml", "", "//comment", 0
5 );
6 }
7
8 void test_qml_comment_entities() {
9 test_parser_verify_entity(
10 test_parser_sourcefile("qml", " //comment"),
11 "comment", "//comment"
12 );
13 test_parser_verify_entity(
14 test_parser_sourcefile("qml", " /*comment*/"),
15 "comment", "/*comment*/"
16 );
17 }
18
19 void all_qml_tests() {
20 test_qml_comments();
21 test_qml_comment_entities();
22 }
0 /* renamed from lisp unit tests...
1 * lots more possible here.
2 */
3
4 void test_racket_comment() {
5 test_parser_verify_parse(
6 test_parser_sourcefile("racket", " ;;; comment"),
7 "racket", "", ";;; comment", 0
8 );
9 }
10
11 void test_racket_doc_string() {
12 test_parser_verify_parse(
13 test_parser_sourcefile("racket", " \"\"\" comment \"\"\""),
14 "racket", "", "\"\"\" comment \"\"\"", 0
15 );
16 }
17
18 void test_racket_doc_string_blank() {
19 test_parser_verify_parse(
20 test_parser_sourcefile("racket", " \"\"\"\"\"\""),
21 "racket", "", "\"\"\"\"\"\"", 0
22 );
23 }
24
25 void test_racket_empty_string() {
26 test_parser_verify_parse(
27 test_parser_sourcefile("racket", "\"\""),
28 "racket", "\"\"", "", 0
29 );
30 }
31
32 void test_racket_char_string() {
33 test_parser_verify_parse(
34 test_parser_sourcefile("racket", " \"a\""),
35 "racket", "\"a\"", "", 0
36 );
37 }
38
39 void test_racket_comment_entities() {
40 test_parser_verify_entity(
41 test_parser_sourcefile("racket", " ;comment"),
42 "comment", ";comment"
43 );
44 }
45
46 void all_racket_tests() {
47 test_racket_comment();
48 test_racket_doc_string();
49 test_racket_doc_string_blank();
50 test_racket_empty_string();
51 test_racket_char_string();
52 test_racket_comment_entities();
53 }
0
1 void test_rebol_comments() {
2 test_parser_verify_parse(
3 test_parser_sourcefile("rebol", "REBOL []\n;comment"),
4 "rebol", "REBOL []\n", ";comment", 0
5 );
6 test_parser_verify_parse(
7 test_parser_sourcefile("rebol", "{}"),
8 "rebol", "{}", "", 0
9 );
10 test_parser_verify_parse(
11 test_parser_sourcefile("rebol", "{{}}"),
12 "rebol", "{{}}", "", 0
13 );
14 test_parser_verify_parse(
15 test_parser_sourcefile("rebol", "{{\n}}"),
16 "rebol", "{{\n}}", "", 0
17 );
18 test_parser_verify_parse(
19 test_parser_sourcefile("rebol", "{\n;inside string\n}"),
20 "rebol", "{\n;inside string\n}", "", 0
21 );
22 test_parser_verify_parse(
23 test_parser_sourcefile("rebol", "{}\n;comment"),
24 "rebol", "{}\n", ";comment", 0
25 );
26 }
27
28 void test_rebol_comment_entities() {
29 test_parser_verify_entity(
30 test_parser_sourcefile("rebol", " ;comment"),
31 "comment", ";comment"
32 );
33 test_parser_verify_entity(
34 test_parser_sourcefile("rebol", " \";no comment\""),
35 "string", "\";no comment\""
36 );
37 }
38
39 void all_rebol_tests() {
40 test_rebol_comments();
41 test_rebol_comment_entities();
42 }
0
1 void test_typescript_comments() {
2 test_parser_verify_parse(
3 test_parser_sourcefile("typescript", " //comment"),
4 "typescript", "", "//comment", 0
5 );
6 }
7
8 void test_typescript_comment_entities() {
9 test_parser_verify_entity(
10 test_parser_sourcefile("typescript", " //comment"),
11 "comment", "//comment"
12 );
13 test_parser_verify_entity(
14 test_parser_sourcefile("typescript", " /*comment*/"),
15 "comment", "/*comment*/"
16 );
17 }
18
19 void all_typescript_tests() {
20 test_typescript_comments();
21 test_typescript_comment_entities();
22 }
0 import unittest
1 import ohcount
2
3 class TestSourceFileList(unittest.TestCase):
4
5 def setUp(self):
6 # must not raise
7 self.sf_list = ohcount.SourceFileList(paths=['../../gestalt_files'])
8
9 def assertStrOp(self, obj, not_equals):
10 s = str(obj)
11 if not_equals:
12 for v in not_equals:
13 self.assertTrue(s is not v)
14
15 def assertHasAttr(self, obj, name, not_equals=None):
16 self.assertTrue(hasattr(obj, name))
17 if not_equals:
18 val = getattr(obj, name)
19 for v in not_equals:
20 self.assertTrue(val is not v)
21
22 def assertHasItem(self, obj, name, not_equals=None):
23 self.assertTrue(name in obj)
24 if not_equals:
25 val = obj[name]
26 for v in not_equals:
27 self.assertTrue(val is not v)
28
29 def assertHasItemAttr(self, obj, name, not_equals=None):
30 self.assertHasAttr(obj, name, not_equals)
31 self.assertHasItem(obj, name, not_equals)
32
33 def assertHasKeys(self, obj, keylist):
34 for k in keylist:
35 self.assertTrue(k in obj)
36
37 def assertListIsInstance(self, list, type):
38 for o in list:
39 self.assertTrue(isinstance(o, type))
40
41 def assertHasItemAttrs(self, obj, list, not_equals=None):
42 for name in list:
43 self.assertHasItemAttr(obj, name, not_equals)
44
45 def testList(self):
46 self.assertTrue(len(self.sf_list) > 0)
47 self.assertListIsInstance(self.sf_list, ohcount.SourceFile)
48
49 def testStr(self):
50 self.assertStrOp(self.sf_list, [None, ""])
51
52 def testAnalyzeLanguages(self):
53 locs = self.sf_list.analyze_languages()
54 self.assertTrue(isinstance(locs, ohcount.LocList))
55 names = ['code','comments','blanks','filecount','total']
56 self.assertHasKeys(locs, names)
57 self.assertHasItemAttrs(locs, names, [None, 0])
58 self.assertListIsInstance(locs, ohcount.Loc)
59
60 def testAddDirectory(self):
61 self.sf_list.add_directory('../../detect_files') # must not raise
62
63 def testAddFile(self):
64 self.sf_list.add_file('../../src_licenses/academic_t1.c') # must not raise
65
66 if __name__ == '__main__':
67 unittest.main()
3030 def test_eclipse_platform
3131 assert_gestalts 'eclipse_platform', [
3232 Base.new(:platform,'java'),
33 Base.new(:platform,'eclipseplatform'),
34 Base.new(:java_import,"java.text.SimpleDateFormat"),
35 Base.new(:java_import,"java.util.Map"),
36 Base.new(:java_import,"org.eclipse.core")
33 Base.new(:platform,'eclipseplatform')
3734 ]
3835 end
3936
4744 assert_gestalts 'win32_enough', [
4845 Base.new(:platform, 'win32'),
4946 Base.new(:platform, 'native_code')
50 ]
51 end
52
53 def test_wpf
54 assert_gestalts 'wpf', [
55 Base.new(:platform, 'wpf')
56 ]
57 end
58
59 def test_asp_net
60 assert_gestalts 'asp_net', [
61 Base.new(:platform, 'asp_net')
6247 ]
6348 end
6449
9984 def test_spring_framework
10085 assert_gestalts 'spring_framework', [
10186 Base.new(:platform, 'java'),
102 Base.new(:platform, 'springframework'),
103 Base.new(:java_jar, 'spring.jar'),
87 Base.new(:platform, 'springframework')
10488 ]
10589 end
10690
172156 assert_tool('netbeans', :netbeans)
173157 end
174158
175 def test_java_imports_from_java_file
176 java = SourceFile.new("foo.java", :contents => <<-INLINE_C
177 import com.foo;
178 import net.ohloh;
179 import com.foo;
180 // import dont.import.this;
181 INLINE_C
182 )
183
184 expected_gestalts = [
185 Base.new(:java_import, 'com.foo', 2),
186 Base.new(:java_import, 'net.ohloh'),
187 Base.new(:platform, 'java'),
188 ]
189
190 assert_equal expected_gestalts.sort, java.gestalts.sort
191 end
192
193159 def test_arm
194160 asm = SourceFile.new("foo.S", :contents => <<-INLINE_ASM
195161 orrs 3, eax
227193 ]
228194
229195 assert_equal expected_gestalts.sort, asm.gestalts.sort
230 end
231
232 def test_imports_from_java_file
233 jar = SourceFile.new("foo/foo.jar", :contents => '')
234
235 expected_gestalts = [
236 Base.new(:java_jar, 'foo.jar'),
237 ]
238
239 assert_equal expected_gestalts.sort, jar.gestalts.sort
240196 end
241197
242198 def test_moblin_clutter
307263 INLINE_C
308264 )
309265
310 expected_gestalts = [
311 Base.new(:java_import, 'android.app.Activity'),
312 Base.new(:platform, 'java'),
313 Base.new(:platform, 'android'),
314 Base.new(:platform, 'mid_combined')
315 ]
316
317 assert_equal expected_gestalts.sort, java.gestalts.sort
266 names = java.gestalts.map { |g| g.name if g.type == :platform }.compact
267 assert names.include?('java')
268 assert names.include?('android')
269 assert names.include?('mid_combined')
318270 end
319271
320272 def test_iphone
417369 import com.sun.identity.authentication;
418370 INLINE_JAVA
419371 )
420 expected_gestalts = [
421 Base.new(:platform, 'java'),
422 Base.new(:platform, 'opensso'),
423 Base.new(:java_import, 'com.sun.identity')
424 ]
425
426 assert_equal expected_gestalts.sort, java.gestalts.sort
372 platforms = java.gestalts.map { |g| g.name if g.type == :platform }.compact
373 assert platforms.include?('java')
374 assert platforms.include?('opensso')
427375 end
428376
429377 def test_windows_ce
22 include Ohcount
33 include Ohcount::Gestalt
44
5 class DotNetDefinitionsTest < Test::Unit::TestCase
5 class DotNetDefinitionsTest < Ohcount::Test
66
7 def test_nunit
8 sf = SourceFile.new('foo.cs', :contents => <<-CONTENTS
9 using NUnit.Framework;
10 CONTENTS
11 )
12 assert_equal [
13 Gestalt::Base.new(:platform, 'dot_net'),
14 Gestalt::Base.new(:platform, 'nunit')
15 ], sf.gestalts.sort
16 end
7 def test_wpf
8 platforms = get_gestalts('wpf').map { |g| g.name if g.type == :platform }.compact
9 assert platforms.include?("dot_net")
10 assert platforms.include?("wpf")
11 end
1712
18 def test_nhibernate
19 sf = SourceFile.new('foo.cs', :contents => <<-CONTENTS
20 using NHibernate.Connection.DriverConnectionProvider;
21 CONTENTS
22 )
23 assert_equal [
24 Gestalt::Base.new(:platform, 'dot_net'),
25 Gestalt::Base.new(:platform, 'nhibernate')
26 ], sf.gestalts.sort
27 end
13 def test_asp_net
14 platforms = get_gestalts('asp_net').map { |g| g.name if g.type == :platform }.compact
15 assert platforms.include?("dot_net")
16 assert platforms.include?("asp_net")
17 end
2818
29 def test_remoting_implies_enterprise
30 sf = SourceFile.new('foo.cs', :contents => <<-CONTENTS
31 using System.Runtime.Remoting;
32 CONTENTS
33 )
34 assert_equal [
35 Gestalt::Base.new(:platform, 'dot_net'),
36 Gestalt::Base.new(:platform, 'dot_net_enterprise')
37 ], sf.gestalts.sort
38 end
39
40 def test_biztalk_implies_enterprise
41 sf = SourceFile.new('foo.cs', :contents => <<-CONTENTS
42 using Microsoft.BizTalk;
43 CONTENTS
44 )
45 assert_equal [
46 Gestalt::Base.new(:platform, 'dot_net'),
47 Gestalt::Base.new(:platform, 'dot_net_biztalk'),
48 Gestalt::Base.new(:platform, 'dot_net_enterprise')
49 ], sf.gestalts.sort
50 end
51
52 def test_linq_implies_enterprise
53 sf = SourceFile.new('foo.cs', :contents => <<-CONTENTS
54 using System.Data.Linq;
55 CONTENTS
56 )
57 assert_equal [
58 Gestalt::Base.new(:platform, 'dot_net'),
59 Gestalt::Base.new(:platform, 'dot_net_enterprise')
60 ], sf.gestalts.sort
61 end
6219
6320 def test_silverlight_via_asp_keyword
6421 sf = SourceFile.new('foo.aspx', :contents => <<-CONTENTS
6724 </body>
6825 CONTENTS
6926 )
70 assert_equal [
71 Gestalt::Base.new(:platform, 'asp_net'),
72 Gestalt::Base.new(:platform, 'silverlight')
73 ], sf.gestalts.sort
27 platforms = sf.gestalts.map { |g| g.name if g.type == :platform }.compact
28 assert platforms.include?('dot_net')
29 assert platforms.include?('asp_net')
30 assert platforms.include?('silverlight')
7431 end
7532
7633 def test_silverlight_via_csproj_import
8037 </Project>
8138 CONTENTS
8239 )
83 assert_equal([
84 Gestalt::Base.new(:platform, 'silverlight'),
85 Gestalt::Base.new(:tool, 'visualstudio')
86 ], sf.gestalts.sort)
40 platforms = sf.gestalts.map { |g| g.name if g.type == :platform }.compact
41 assert platforms.include?('dot_net')
42 assert platforms.include?('silverlight')
43
44 tools = sf.gestalts.map { |g| g.name if g.type == :tool }.compact
45 assert tools.include?('visualstudio')
8746 end
8847 end
+0
-32
test/unit/ruby/gestalt/find_java_imports_rule_test.rb less more
0 require File.dirname(__FILE__) + '/../../test_helper'
1
2 class FindJavaImportsRuleTest < Test::Unit::TestCase
3 include Ohcount::Gestalt
4
5 def test_truncate_name
6 assert_equal "", FindJavaImportsRule.truncate_name(nil, 3)
7 assert_equal "", FindJavaImportsRule.truncate_name("", 3)
8 assert_equal "", FindJavaImportsRule.truncate_name("net.ohloh.ohcount.test", 0)
9 assert_equal "net", FindJavaImportsRule.truncate_name("net.ohloh.ohcount.test", 1)
10 assert_equal "net.ohloh", FindJavaImportsRule.truncate_name("net.ohloh.ohcount.test", 2)
11 assert_equal "net.ohloh.ohcount", FindJavaImportsRule.truncate_name("net.ohloh.ohcount.test", 3)
12 assert_equal "net.ohloh.ohcount.test", FindJavaImportsRule.truncate_name("net.ohloh.ohcount.test", 4)
13 assert_equal "net.ohloh.ohcount.test", FindJavaImportsRule.truncate_name("net.ohloh.ohcount.test", 5)
14 end
15
16 def test_arm_from_java_import
17 java = SourceFile.new("foo.java", :contents => <<-INLINE_C
18 import org.opengroup.arm40.transaction.ArmConstants;
19 // import dont.import.this;
20 INLINE_C
21 )
22
23 expected_gestalts = [
24 Base.new(:java_import, 'org.opengroup.arm40'),
25 Base.new(:platform, 'Java'),
26 Base.new(:platform, 'arm'),
27 ]
28
29 assert_equal expected_gestalts.sort, java.gestalts.sort
30 end
31 end
00 require 'test/unit'
1 require File.dirname(__FILE__) + '/../../../ruby/gestalt'
1 require_relative '../../../ruby/gestalt'
22
33 class SourceFileTest < Test::Unit::TestCase
44 def test_diff
5 c = File.open(File.dirname(__FILE__) + "/../../src_dir/optimer").read
6 new = Ohcount::SourceFile.new("optimer", :contents => c, :filenames => nil, :filenames => ["optimer"])
5 optimer = File.open(File.dirname(__FILE__) + "/../../src_dir/optimer").read
6 new = Ohcount::SourceFile.new("optimer", :contents => optimer, :filenames => nil, :filenames => ["optimer"])
77 old = Ohcount::SourceFile.new("optimer", :contents => "", :filenames => ["optimer"])
8 assert_equal c, new.contents
8 assert_equal optimer, new.contents
99 deltas = old.diff(new).loc_deltas
1010 assert_not_nil deltas
1111 assert_equal "shell", deltas.first.language
4646 end
4747
4848 def assert_gestalts(path, expected_gestalts)
49 assert_equal expected_gestalts.sort, get_gestalts(path)
50 end
51
52 def get_gestalts(path)
4953 sfl = SourceFileList.new(:paths => [test_dir(path)])
5054 assert sfl.size > 0
5155 sfl.analyze(:gestalt)
52 assert_equal expected_gestalts.sort, sfl.gestalts.sort
53 end
56 sfl.gestalts.sort
57 end
5458
5559 def test_dir(d)
5660 File.expand_path(File.dirname(__FILE__) + "/../../gestalt_files/#{ d }")
202202
203203 void test_sourcefile_list_language_facts() {
204204 SourceFileList *sfl = ohcount_sourcefile_list_new();
205 ohcount_sourcefile_list_add_directory(sfl, "../gestalt_files/win32_enough/");
205 ohcount_sourcefile_list_add_directory(sfl, "../gestalt_files/win32_enough");
206206 LocList *list = ohcount_sourcefile_list_analyze_languages(sfl);
207207 assert(ohcount_loc_list_filecount(list) == 2);
208208 Loc *loc = ohcount_loc_list_get_loc(list, "c");
213213 ohcount_loc_list_free(list);
214214 }
215215
216 void test_sourcefile_list_no_symlink_dir() {
217 SourceFileList *sfl = ohcount_sourcefile_list_new();
218 ohcount_sourcefile_list_add_directory(sfl, "../symlink_test_dir");
219 LocList *list = ohcount_sourcefile_list_analyze_languages(sfl);
220 assert(ohcount_loc_list_filecount(list) == 0);
221 ohcount_sourcefile_list_free(sfl);
222 ohcount_loc_list_free(list);
223 }
224
225 #define FALSE 0
226 #define TRUE 1
227 char *tmp_file_from_buf(const char *buf);
228
229 void test_tmp_dir() {
230 char buf[] = "This is just some bogus text.";
231 char *tmp_path = tmp_file_from_buf(buf);
232
233 SourceFileList *list = ohcount_sourcefile_list_new();
234 ohcount_sourcefile_list_add_directory(list, "/tmp");
235 int has_tmp = FALSE;
236 SourceFileList *iter = list->head;
237
238 for (; iter != NULL; iter = iter->next) {
239 if (strcmp(iter->sf->filepath, tmp_path) == 0) {
240 has_tmp = TRUE;
241 break;
242 }
243 }
244 assert(has_tmp);
245 }
246
247
216248 void all_sourcefile_tests() {
217249 test_sourcefile_initialize();
218250 test_sourcefile_language_breakdowns();
223255 test_sourcefile_calc_diff();
224256
225257 test_sourcefile_list_language_facts();
226 }
258 test_sourcefile_list_no_symlink_dir();
259 test_tmp_dir();
260 }