ModelicaStrings.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. /* ModelicaStrings.c - External functions for Modelica.Functions.Strings
  2. Copyright (C) 2002-2016, Modelica Association and DLR
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. 1. Redistributions of source code must retain the above copyright notice,
  7. this list of conditions and the following disclaimer.
  8. 2. Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  12. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  13. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  14. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  15. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  16. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  17. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  18. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  19. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  20. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  21. */
  22. /* The functions are mostly non-portable. The following #define's are used
  23. to define the system calls of the operating system
  24. _MSC_VER : Microsoft Visual C++
  25. __GNUC__ : GNU C compiler
  26. MODELICA_EXPORT: Prefix used for function calls. If not defined, blank is used
  27. Useful definitions:
  28. - "static" that is all functions become static
  29. (useful if file is included with other C-sources for an
  30. embedded system)
  31. - "__declspec(dllexport)" if included in a DLL and the
  32. functions shall be visible outside of the DLL
  33. Release Notes:
  34. Feb. 26, 2016: by Hans Olsson, DS AB
  35. Build hash code on the unsigned characters in
  36. ModelicaStrings_hashString (ticket #1926)
  37. Oct. 27, 2015: by Thomas Beutlich, ITI GmbH
  38. Added nonnull attributes/annotations (ticket #1436)
  39. Oct. 05, 2015: by Thomas Beutlich, ITI GmbH
  40. Added function ModelicaStrings_hashString from ModelicaRandom.c
  41. of https://github.com/DLR-SR/Noise (ticket #1662)
  42. Mar. 26, 2013: by Martin Otter, DLR
  43. Introduced three (int) casts to avoid warning messages (ticket #1032)
  44. Jan. 11, 2013: by Jesper Mattsson, Modelon AB
  45. Made code C89 compatible
  46. Jan. 5, 2013: by Martin Otter, DLR
  47. Removed "static" declarations from the Modelica interface functions
  48. Sep. 24, 2004: by Martin Otter, DLR
  49. Final cleaning up of the code
  50. Sep. 9, 2004: by Dag Bruck, Dynasim AB
  51. Implementation of scan functions
  52. Aug. 19, 2004: by Martin Otter, DLR
  53. Changed according to the decisions of the 37th
  54. design meeting in Lund (see minutes)
  55. Jan. 7, 2002: by Martin Otter, DLR
  56. Implemented a first version
  57. */
  58. #include <ctype.h>
  59. #if !defined(NO_FILE_SYSTEM)
  60. #include <stdio.h>
  61. #endif
  62. #include <string.h>
  63. #include "ModelicaUtilities.h"
  64. #include "localeless.h"
  65. #if !defined(MODELICA_EXPORT)
  66. #define MODELICA_EXPORT DYMOLA_STATIC
  67. #endif
  68. static const char* ModelicaStrings_substring(const char* string, int startIndex, int endIndex) {
  69. /* Return string1(startIndex:endIndex) if endIndex >= startIndex,
  70. or return string1(startIndex:startIndex), if endIndex = 0.
  71. An assert is triggered, if startIndex/endIndex are not valid.
  72. */
  73. char* substring;
  74. int len1 = strlen(string);
  75. int len2;
  76. /* Check arguments */
  77. if ( startIndex < 1 ) {
  78. ModelicaFormatError("Wrong call of Utilities.Strings.substring:\n"
  79. " startIndex = %d (has to be > 0).\n"
  80. " string = \"%s\"\n", startIndex, string);
  81. } else if ( endIndex == -999 ) {
  82. endIndex = startIndex;
  83. } else if ( endIndex < startIndex ) {
  84. ModelicaFormatError("Wrong call of Utilities.Strings.substring:\n"
  85. " startIndex = %d\n"
  86. " endIndex = %d (>= startIndex required)\n"
  87. " string = \"%s\"\n", startIndex, endIndex, string);
  88. } else if ( endIndex > len1 ) {
  89. ModelicaFormatError("Wrong call of Utilities.Strings.substring:\n"
  90. " endIndex = %d (<= %d required (=length(string)).\n"
  91. " string = \"%s\"\n", endIndex, len1, string);
  92. };
  93. /* Allocate memory and copy string */
  94. len2 = endIndex - startIndex + 1;
  95. substring = ModelicaAllocateString(len2);
  96. strncpy(substring, &string[startIndex-1], len2);
  97. substring[len2] = '\0';
  98. return substring;
  99. };
  100. static int ModelicaStrings_length(const char* string)
  101. /* Returns the number of characters "string" */
  102. {
  103. return strlen(string);
  104. }
  105. static int ModelicaStrings_compare(const char* string1, const char* string2, int caseSensitive)
  106. /* compares two strings, optionally ignoring case */
  107. {
  108. int result;
  109. if (string1 == 0 || string2 == 0) return 2;
  110. if (caseSensitive) {
  111. result = strcmp(string1, string2);
  112. } else {
  113. while (tolowerC(*string1) == tolowerC(*string2) && *string1 != '\0') {
  114. string1++;
  115. string2++;
  116. }
  117. result = (int)(tolowerC(*string1)) - (int)(tolowerC(*string2));
  118. }
  119. if ( result < 0 ) {
  120. result = 1;
  121. } else if ( result == 0 ) {
  122. result = 2;
  123. } else {
  124. result = 3;
  125. };
  126. return result;
  127. }
  128. #define MAX_TOKEN_SIZE 100
  129. static int ModelicaStrings_skipWhiteSpace(const char* string, int i)
  130. /* Return index in string after skipping ws, or position of terminating nul. */
  131. {
  132. while (string[i-1] != '\0' && isspaceC(string[i-1]))
  133. ++i;
  134. return i;
  135. }
  136. /* ----------------- utility functions used in scanXXX functions ----------- */
  137. static int InSet(const char* string, int i, const char* separators)
  138. /* Returns true if string[i] is one of the characters in separators. */
  139. {
  140. return strchr(separators, string[i-1]) != NULL;
  141. }
  142. static int SkipNonWhiteSpaceSeparator(const char* string, int i, const char* separators)
  143. /* Return index in string of first character which is ws or character in separators,
  144. or position of terminating nul. */
  145. {
  146. while (string[i-1] != '\0' && (isspaceC(string[i-1]) || InSet(string, i, separators)))
  147. ++i;
  148. return i;
  149. }
  150. static int get_token(const char* string, int startIndex, const char* separators,
  151. int* output_index, int* token_start, int* token_length)
  152. {
  153. int past_token;
  154. int sep_pos;
  155. *token_start = ModelicaStrings_skipWhiteSpace(string, startIndex);
  156. /* Index of first char of token, after ws. */
  157. past_token = SkipNonWhiteSpaceSeparator(string, *token_start, separators);
  158. /* Index of first char after token, ws or separator. */
  159. sep_pos = ModelicaStrings_skipWhiteSpace(string, past_token);
  160. /* Index of first char after ws after token, maybe a separator. */
  161. *output_index = InSet(string, sep_pos, separators) ? sep_pos + 1 : sep_pos;
  162. /* Skip any separator. */
  163. *token_length = past_token-*token_start;
  164. if (*token_length == 0 || *token_length > MAX_TOKEN_SIZE) {
  165. /* Token missing or too long. */
  166. *output_index = startIndex;
  167. return 0; /* error */
  168. }
  169. return 1; /* ok */
  170. }
  171. static int MatchUnsignedInteger(const char* string, int start)
  172. /* Starts matching character which make an unsigned integer. The matching
  173. begins at the start index (first char has index 1). Returns the number
  174. of characters that could be matched, or zero if the first character
  175. was not a digit. */
  176. {
  177. const char* begin = &string[start-1];
  178. const char* p = begin;
  179. while (*p != '\0' && isdigitC(*p))
  180. ++p;
  181. return p - begin;
  182. }
  183. /* --------------- end of utility functions used in scanXXX functions ----------- */
  184. static void ModelicaStrings_scanIdentifier(const char* string, int startIndex, int* nextIndex, const char** identifier)
  185. {
  186. int token_length=0;
  187. int token_start = ModelicaStrings_skipWhiteSpace(string, startIndex);
  188. /* Index of first char of token, after ws. */
  189. if (isalphaC(string[token_start-1])) {
  190. /* Identifier has begun. */
  191. token_length = 1;
  192. while (string[token_start+token_length-1] != '\0' &&
  193. (isalphaC(string[token_start+token_length-1]) ||
  194. isdigitC(string[token_start+token_length-1]) ||
  195. string[token_start+token_length-1] == '_'))
  196. {
  197. ++token_length;
  198. }
  199. {
  200. char* s = ModelicaAllocateString(token_length);
  201. strncpy(s, string+token_start-1, token_length);
  202. s[token_length] = '\0';
  203. *nextIndex = token_start + token_length;
  204. *identifier = s;
  205. return;
  206. }
  207. }
  208. /* Token missing or not identifier. */
  209. *nextIndex = startIndex;
  210. *identifier = ModelicaAllocateString(0);
  211. return;
  212. }
  213. static void ModelicaStrings_scanInteger(const char* string, int startIndex, int unsignedNumber,
  214. int* nextIndex, int* integerNumber)
  215. {
  216. int number_length=0;
  217. int sign = 0;
  218. /* Number of characters used for sign. */
  219. int token_start = ModelicaStrings_skipWhiteSpace(string, startIndex);
  220. /* Index of first char of token, after ws. */
  221. if (string[token_start-1] == '+' || string[token_start-1] == '-')
  222. sign = 1;
  223. if (unsignedNumber==0 || (unsignedNumber==1 && sign==0)) {
  224. number_length = MatchUnsignedInteger(string, token_start + sign);
  225. /* Number of characters in unsigned number. */
  226. if (number_length > 0 && sign + number_length < MAX_TOKEN_SIZE) {
  227. /* check if the scanned string is no Real number */
  228. int next = token_start + sign + number_length - 1;
  229. if ( string[next] == '\0' ||
  230. (string[next] != '\0' && string[next] != '.'
  231. && string[next] != 'e'
  232. && string[next] != 'E') ) {
  233. /* get Integer value */
  234. char buf[MAX_TOKEN_SIZE+1];
  235. int x;
  236. strncpy(buf, string+token_start-1, sign + number_length);
  237. buf[sign + number_length] = '\0';
  238. #if !defined(NO_FILE_SYSTEM)
  239. if (sscanfCd(buf, &x) == 1) {
  240. *integerNumber = x;
  241. *nextIndex = token_start + sign + number_length;
  242. return;
  243. }
  244. #endif
  245. } else {
  246. ++number_length;
  247. }
  248. }
  249. }
  250. /* Token missing or cannot be converted to result type. */
  251. *nextIndex = startIndex;
  252. *integerNumber = 0;
  253. return;
  254. }
  255. static void ModelicaStrings_scanReal(const char* string, int startIndex, int unsignedNumber,
  256. int* nextIndex, double* number)
  257. {
  258. /*
  259. Grammar of real number:
  260. real ::= [sign] unsigned [fraction] [exponent]
  261. sign ::= '+' | '-'
  262. unsigned ::= digit [unsigned]
  263. fraction ::= '.' [unsigned]
  264. exponent ::= ('e' | 'E') [sign] unsigned
  265. digit ::= '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'
  266. */
  267. int len = 0;
  268. /* Temporary variable for the length of a matched unsigned number. */
  269. int total_length = 0;
  270. /* Total number of characters recognized as part of a decimal number. */
  271. int token_start = ModelicaStrings_skipWhiteSpace(string, startIndex);
  272. /* Index of first char of token, after ws. */
  273. /* Scan sign of decimal number */
  274. if (string[token_start-1] == '+' || string[token_start-1] == '-') {
  275. total_length = 1;
  276. if (unsignedNumber==1) goto error;
  277. }
  278. /* Scan integer part of mantissa. */
  279. len = MatchUnsignedInteger(string, token_start + total_length);
  280. total_length += len;
  281. /* Scan decimal part of mantissa. */
  282. if (string[token_start + total_length-1] == '.') {
  283. total_length += 1;
  284. len = MatchUnsignedInteger(string, token_start + total_length);
  285. if (len > 0) {
  286. total_length += len;
  287. }
  288. }
  289. /* Scan exponent part of mantissa. */
  290. if (string[token_start + total_length-1] == 'e' || string[token_start + total_length-1] == 'E') {
  291. int exp_len = 1;
  292. if (string[token_start + total_length] == '+' || string[token_start + total_length] == '-') {
  293. exp_len += 1;
  294. }
  295. len = MatchUnsignedInteger(string, token_start + total_length + exp_len);
  296. if (len == 0) goto error;
  297. total_length += exp_len + len;
  298. }
  299. /* Convert accumulated characters into a number. */
  300. if (total_length > 0 && total_length < MAX_TOKEN_SIZE) {
  301. char buf[MAX_TOKEN_SIZE+1];
  302. double x;
  303. strncpy(buf, string+token_start-1, total_length);
  304. buf[total_length] = '\0';
  305. #if !defined(NO_FILE_SYSTEM)
  306. if (sscanfClg(buf, &x) == 1) {
  307. *number = x;
  308. *nextIndex = token_start + total_length;
  309. return;
  310. }
  311. #endif
  312. }
  313. /* Token missing or cannot be converted to result type. */
  314. error:
  315. *nextIndex = startIndex;
  316. *number = 0;
  317. return;
  318. }
  319. static void ModelicaStrings_scanString(const char* string, int startIndex,
  320. int* nextIndex, const char** result)
  321. {
  322. int i, token_start, past_token, token_length;
  323. token_length = 0;
  324. token_start = ModelicaStrings_skipWhiteSpace(string, startIndex);
  325. i = token_start;
  326. if (string[token_start-1] != '"') goto error;
  327. /* Index of first char of token, after ws. */
  328. ++i;
  329. while (1) {
  330. if (string[i-1] == '\0') goto error;
  331. if (string[i-2] == '\\' && string[i-1] == '"')
  332. ; /* escaped quote, consume */
  333. else if (string[i-1] == '"')
  334. break; /* end quote */
  335. ++i;
  336. }
  337. past_token = i + 1;
  338. /* Index of first char after token, ws or separator. */
  339. token_length = past_token-token_start-2;
  340. if (token_length > 0) {
  341. char* s = ModelicaAllocateString(token_length);
  342. strncpy(s, string+token_start, token_length);
  343. s[token_length] = '\0';
  344. *result = s;
  345. *nextIndex = past_token;
  346. return;
  347. }
  348. error:
  349. *result = ModelicaAllocateString(0);
  350. *nextIndex = startIndex;
  351. return;
  352. }
  353. MODELICA_EXPORT int ModelicaStrings_hashString(const char* inStr) {
  354. /* Compute an unsigned int hash code from a character string
  355. *
  356. * Author: Arash Partow - 2002 *
  357. * URL: http://www.partow.net *
  358. * URL: http://www.partow.net/programming/hashfunctions/index.html *
  359. * *
  360. * Copyright notice: *
  361. * Free use of the General Purpose Hash Function Algorithms Library is *
  362. * permitted under the guidelines and in accordance with the most current *
  363. * version of the Common Public License. *
  364. * http://www.opensource.org/licenses/cpl1.0.php *
  365. */
  366. unsigned int hash = 0xAAAAAAAA;
  367. unsigned int i = 0;
  368. unsigned int len = (unsigned int)strlen(inStr);
  369. const unsigned char *str =(const unsigned char*)(inStr);
  370. /* Use unsigned char to be independent of compiler settings, */
  371. /* https://trac.modelica.org/Modelica/ticket/1926 */
  372. union hash_tag {
  373. unsigned int iu;
  374. int is;
  375. } h;
  376. for(i = 0; i < len; str++, i++) {
  377. hash ^= ((i & 1) == 0) ? ( (hash << 7) ^ (*str) * (hash >> 3)) :
  378. (~((hash << 11) + ((*str) ^ (hash >> 5))));
  379. }
  380. h.iu = hash;
  381. return h.is;
  382. }