You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

831 lines
21 KiB

15 years ago
15 years ago
15 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
15 years ago
15 years ago
13 years ago
13 years ago
  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2007-2013 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
  5. * Copyright (C) 2007-2015 KiCad Developers, see change_log.txt for contributors.
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU General Public License
  9. * as published by the Free Software Foundation; either version 2
  10. * of the License, or (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, you may find one here:
  19. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  20. * or you may search the http://www.gnu.org website for the version 2 license,
  21. * or you may write to the Free Software Foundation, Inc.,
  22. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  23. */
  24. #include <cstdarg>
  25. #include <cstdio>
  26. #include <cstdlib> // bsearch()
  27. #include <cctype>
  28. #include <macros.h>
  29. #include <fctsys.h>
  30. #include <dsnlexer.h>
  31. //#define STANDALONE 1 // enable this for stand alone testing.
  32. #define FMT_CLIPBOARD _( "clipboard" )
  33. //-----<DSNLEXER>-------------------------------------------------------------
  34. void DSNLEXER::init()
  35. {
  36. curTok = DSN_NONE;
  37. prevTok = DSN_NONE;
  38. stringDelimiter = '"';
  39. specctraMode = false;
  40. space_in_quoted_tokens = false;
  41. commentsAreTokens = false;
  42. curOffset = 0;
  43. #if 1
  44. if( keywordCount > 11 )
  45. {
  46. // resize the hashtable bucket count
  47. keyword_hash.reserve( keywordCount );
  48. }
  49. // fill the specialized "C string" hashtable from keywords[]
  50. const KEYWORD* it = keywords;
  51. const KEYWORD* end = it + keywordCount;
  52. for( ; it < end; ++it )
  53. {
  54. keyword_hash[it->name] = it->token;
  55. }
  56. #endif
  57. }
  58. DSNLEXER::DSNLEXER( const KEYWORD* aKeywordTable, unsigned aKeywordCount,
  59. FILE* aFile, const wxString& aFilename ) :
  60. iOwnReaders( true ),
  61. start( NULL ),
  62. next( NULL ),
  63. limit( NULL ),
  64. reader( NULL ),
  65. keywords( aKeywordTable ),
  66. keywordCount( aKeywordCount )
  67. {
  68. FILE_LINE_READER* fileReader = new FILE_LINE_READER( aFile, aFilename );
  69. PushReader( fileReader );
  70. init();
  71. }
  72. DSNLEXER::DSNLEXER( const KEYWORD* aKeywordTable, unsigned aKeywordCount,
  73. const std::string& aClipboardTxt, const wxString& aSource ) :
  74. iOwnReaders( true ),
  75. start( NULL ),
  76. next( NULL ),
  77. limit( NULL ),
  78. reader( NULL ),
  79. keywords( aKeywordTable ),
  80. keywordCount( aKeywordCount )
  81. {
  82. STRING_LINE_READER* stringReader = new STRING_LINE_READER( aClipboardTxt, aSource.IsEmpty() ?
  83. wxString( FMT_CLIPBOARD ) : aSource );
  84. PushReader( stringReader );
  85. init();
  86. }
  87. DSNLEXER::DSNLEXER( const KEYWORD* aKeywordTable, unsigned aKeywordCount,
  88. LINE_READER* aLineReader ) :
  89. iOwnReaders( false ),
  90. start( NULL ),
  91. next( NULL ),
  92. limit( NULL ),
  93. reader( NULL ),
  94. keywords( aKeywordTable ),
  95. keywordCount( aKeywordCount )
  96. {
  97. if( aLineReader )
  98. PushReader( aLineReader );
  99. init();
  100. }
  101. static const KEYWORD empty_keywords[1] = {};
  102. DSNLEXER::DSNLEXER( const std::string& aSExpression, const wxString& aSource ) :
  103. iOwnReaders( true ),
  104. start( NULL ),
  105. next( NULL ),
  106. limit( NULL ),
  107. reader( NULL ),
  108. keywords( empty_keywords ),
  109. keywordCount( 0 )
  110. {
  111. STRING_LINE_READER* stringReader = new STRING_LINE_READER( aSExpression, aSource.IsEmpty() ?
  112. wxString( FMT_CLIPBOARD ) : aSource );
  113. PushReader( stringReader );
  114. init();
  115. }
  116. DSNLEXER::~DSNLEXER()
  117. {
  118. if( iOwnReaders )
  119. {
  120. // delete the LINE_READERs from the stack, since I own them.
  121. for( READER_STACK::iterator it = readerStack.begin(); it!=readerStack.end(); ++it )
  122. delete *it;
  123. }
  124. }
  125. void DSNLEXER::SetSpecctraMode( bool aMode )
  126. {
  127. specctraMode = aMode;
  128. if( aMode )
  129. {
  130. // specctra mode defaults, some of which can still be changed in this mode.
  131. space_in_quoted_tokens = true;
  132. }
  133. else
  134. {
  135. space_in_quoted_tokens = false;
  136. stringDelimiter = '"';
  137. }
  138. }
  139. bool DSNLEXER::SyncLineReaderWith( DSNLEXER& aLexer )
  140. {
  141. // Synchronize the pointers handling the data read by the LINE_READER
  142. // only if aLexer shares the same LINE_READER, because only in this case
  143. // the char buffer is be common
  144. if( reader != aLexer.reader )
  145. return false;
  146. // We can synchronize the pointers which handle the data currently read
  147. start = aLexer.start;
  148. next = aLexer.next;
  149. limit = aLexer.limit;
  150. // Sync these parameters is not mandatory, but could help
  151. // for instance in debug
  152. curText = aLexer.curText;
  153. curOffset = aLexer.curOffset;
  154. return true;
  155. }
  156. void DSNLEXER::PushReader( LINE_READER* aLineReader )
  157. {
  158. readerStack.push_back( aLineReader );
  159. reader = aLineReader;
  160. start = (const char*) (*reader);
  161. // force a new readLine() as first thing.
  162. limit = start;
  163. next = start;
  164. }
  165. LINE_READER* DSNLEXER::PopReader()
  166. {
  167. LINE_READER* ret = 0;
  168. if( readerStack.size() )
  169. {
  170. ret = reader;
  171. readerStack.pop_back();
  172. if( readerStack.size() )
  173. {
  174. reader = readerStack.back();
  175. start = reader->Line();
  176. // force a new readLine() as first thing.
  177. limit = start;
  178. next = start;
  179. }
  180. else
  181. {
  182. reader = 0;
  183. start = dummy;
  184. limit = dummy;
  185. }
  186. }
  187. return ret;
  188. }
  189. #if 0
  190. static int compare( const void* a1, const void* a2 )
  191. {
  192. const KEYWORD* k1 = (const KEYWORD*) a1;
  193. const KEYWORD* k2 = (const KEYWORD*) a2;
  194. int ret = strcmp( k1->name, k2->name );
  195. return ret;
  196. }
  197. int DSNLEXER::findToken( const std::string& tok )
  198. {
  199. KEYWORD search;
  200. search.name = tok.c_str();
  201. const KEYWORD* findings = (const KEYWORD*) bsearch( &search,
  202. keywords, keywordCount,
  203. sizeof(KEYWORD), compare );
  204. if( findings )
  205. return findings->token;
  206. else
  207. return DSN_SYMBOL; // not a keyword, some arbitrary symbol.
  208. }
  209. #else
  210. inline int DSNLEXER::findToken( const std::string& tok )
  211. {
  212. KEYWORD_MAP::const_iterator it = keyword_hash.find( tok.c_str() );
  213. if( it != keyword_hash.end() )
  214. return it->second;
  215. return DSN_SYMBOL; // not a keyword, some arbitrary symbol.
  216. }
  217. #endif
  218. const char* DSNLEXER::Syntax( int aTok )
  219. {
  220. const char* ret;
  221. switch( aTok )
  222. {
  223. case DSN_NONE:
  224. ret = "NONE";
  225. break;
  226. case DSN_STRING_QUOTE:
  227. ret = "string_quote"; // a special DSN syntax token, see specctra spec.
  228. break;
  229. case DSN_QUOTE_DEF:
  230. ret = "quoted text delimiter";
  231. break;
  232. case DSN_DASH:
  233. ret = "-";
  234. break;
  235. case DSN_SYMBOL:
  236. ret = "symbol";
  237. break;
  238. case DSN_NUMBER:
  239. ret = "number";
  240. break;
  241. case DSN_RIGHT:
  242. ret = ")";
  243. break;
  244. case DSN_LEFT:
  245. ret = "(";
  246. break;
  247. case DSN_STRING:
  248. ret = "quoted string";
  249. break;
  250. case DSN_EOF:
  251. ret = "end of input";
  252. break;
  253. default:
  254. ret = "???";
  255. }
  256. return ret;
  257. }
  258. const char* DSNLEXER::GetTokenText( int aTok )
  259. {
  260. const char* ret;
  261. if( aTok < 0 )
  262. {
  263. return Syntax( aTok );
  264. }
  265. else if( (unsigned) aTok < keywordCount )
  266. {
  267. ret = keywords[aTok].name;
  268. }
  269. else
  270. ret = "token too big";
  271. return ret;
  272. }
  273. wxString DSNLEXER::GetTokenString( int aTok )
  274. {
  275. wxString ret;
  276. ret << wxT("'") << wxString::FromUTF8( GetTokenText(aTok) ) << wxT("'");
  277. return ret;
  278. }
  279. bool DSNLEXER::IsSymbol( int aTok )
  280. {
  281. // This is static and not inline to reduce code space.
  282. // if aTok is >= 0, then it is a coincidental match to a keyword.
  283. return aTok==DSN_SYMBOL || aTok==DSN_STRING || aTok>=0;
  284. }
  285. void DSNLEXER::Expecting( int aTok )
  286. {
  287. wxString errText = wxString::Format(
  288. _( "Expecting %s" ), GetChars( GetTokenString( aTok ) ) );
  289. THROW_PARSE_ERROR( errText, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  290. }
  291. void DSNLEXER::Expecting( const char* text )
  292. {
  293. wxString errText = wxString::Format(
  294. _( "Expecting '%s'" ), GetChars( wxString::FromUTF8( text ) ) );
  295. THROW_PARSE_ERROR( errText, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  296. }
  297. void DSNLEXER::Unexpected( int aTok )
  298. {
  299. wxString errText = wxString::Format(
  300. _( "Unexpected %s" ), GetChars( GetTokenString( aTok ) ) );
  301. THROW_PARSE_ERROR( errText, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  302. }
  303. void DSNLEXER::Duplicate( int aTok )
  304. {
  305. wxString errText = wxString::Format(
  306. _("%s is a duplicate"), GetTokenString( aTok ).GetData() );
  307. THROW_PARSE_ERROR( errText, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  308. }
  309. void DSNLEXER::Unexpected( const char* text )
  310. {
  311. wxString errText = wxString::Format(
  312. _( "Unexpected '%s'" ), GetChars( wxString::FromUTF8( text ) ) );
  313. THROW_PARSE_ERROR( errText, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  314. }
  315. void DSNLEXER::NeedLEFT()
  316. {
  317. int tok = NextTok();
  318. if( tok != DSN_LEFT )
  319. Expecting( DSN_LEFT );
  320. }
  321. void DSNLEXER::NeedRIGHT()
  322. {
  323. int tok = NextTok();
  324. if( tok != DSN_RIGHT )
  325. Expecting( DSN_RIGHT );
  326. }
  327. int DSNLEXER::NeedSYMBOL()
  328. {
  329. int tok = NextTok();
  330. if( !IsSymbol( tok ) )
  331. Expecting( DSN_SYMBOL );
  332. return tok;
  333. }
  334. int DSNLEXER::NeedSYMBOLorNUMBER()
  335. {
  336. int tok = NextTok();
  337. if( !IsSymbol( tok ) && tok!=DSN_NUMBER )
  338. Expecting( "a symbol or number" );
  339. return tok;
  340. }
  341. int DSNLEXER::NeedNUMBER( const char* aExpectation )
  342. {
  343. int tok = NextTok();
  344. if( tok != DSN_NUMBER )
  345. {
  346. wxString errText = wxString::Format(
  347. _( "need a number for '%s'" ), wxString::FromUTF8( aExpectation ).GetData() );
  348. THROW_PARSE_ERROR( errText, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  349. }
  350. return tok;
  351. }
  352. /**
  353. * Function isSpace
  354. * tests for whitespace. Our whitespace, by our definition, is a subset of ASCII,
  355. * i.e. no bytes with MSB on can be considered whitespace, since they are likely part
  356. * of a multibyte UTF8 character.
  357. */
  358. static bool isSpace( char cc )
  359. {
  360. // cc is signed, so it is often negative.
  361. // Treat negative as large positive to exclude rapidly.
  362. if( (unsigned char) cc <= ' ' )
  363. {
  364. switch( (unsigned char) cc )
  365. {
  366. case ' ':
  367. case '\n':
  368. case '\r':
  369. case '\t':
  370. case '\0': // PCAD s-expression files have this.
  371. return true;
  372. }
  373. }
  374. return false;
  375. }
  376. inline bool isDigit( char cc )
  377. {
  378. return '0' <= cc && cc <= '9';
  379. }
  380. /// return true if @a cc is an s-expression separator character
  381. inline bool isSep( char cc )
  382. {
  383. return isSpace( cc ) || cc=='(' || cc==')';
  384. }
  385. /**
  386. * Function isNumber
  387. * returns true if the next sequence of text is a number:
  388. * either an integer, fixed point, or float with exponent. Stops scanning
  389. * at the first non-number character, even if it is not whitespace.
  390. *
  391. * @param cp is the start of the current token.
  392. * @param limit is the end of the current token.
  393. *
  394. * @return bool - true if input token is a number, else false.
  395. */
  396. static bool isNumber( const char* cp, const char* limit )
  397. {
  398. // regex for a float: "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?" i.e. any number,
  399. // code traversal manually here:
  400. bool sawNumber = false;
  401. if( cp < limit && ( *cp=='-' || *cp=='+' ) )
  402. ++cp;
  403. while( cp < limit && isDigit( *cp ) )
  404. {
  405. ++cp;
  406. sawNumber = true;
  407. }
  408. if( cp < limit && *cp == '.' )
  409. {
  410. ++cp;
  411. while( cp < limit && isDigit( *cp ) )
  412. {
  413. ++cp;
  414. sawNumber = true;
  415. }
  416. }
  417. if( sawNumber )
  418. {
  419. if( cp < limit && ( *cp=='E' || *cp=='e' ) )
  420. {
  421. ++cp;
  422. sawNumber = false; // exponent mandates at least one digit thereafter.
  423. if( cp < limit && ( *cp=='-' || *cp=='+' ) )
  424. ++cp;
  425. while( cp < limit && isDigit( *cp ) )
  426. {
  427. ++cp;
  428. sawNumber = true;
  429. }
  430. }
  431. }
  432. return sawNumber && cp==limit;
  433. }
  434. int DSNLEXER::NextTok()
  435. {
  436. const char* cur = next;
  437. const char* head = cur;
  438. prevTok = curTok;
  439. if( curTok == DSN_EOF )
  440. goto exit;
  441. if( cur >= limit )
  442. {
  443. L_read:
  444. // blank lines are returned as "\n" and will have a len of 1.
  445. // EOF will have a len of 0 and so is detectable.
  446. int len = readLine();
  447. if( len == 0 )
  448. {
  449. cur = start; // after readLine(), since start can change, set cur offset to start
  450. curTok = DSN_EOF;
  451. goto exit;
  452. }
  453. cur = start; // after readLine() since start can change.
  454. // skip leading whitespace
  455. while( cur<limit && isSpace( *cur ) )
  456. ++cur;
  457. // If the first non-blank character is #, this line is a comment.
  458. // Comments cannot follow any other token on the same line.
  459. if( cur<limit && *cur=='#' )
  460. {
  461. if( commentsAreTokens )
  462. {
  463. // Grab the entire current line [excluding end of line char(s)] as the
  464. // current token. The '#' character may not be at offset zero.
  465. while( limit[-1] == '\n' || limit[-1] == '\r' )
  466. --limit;
  467. curText.clear();
  468. curText.append( start, limit );
  469. cur = start; // ensure a good curOffset below
  470. curTok = DSN_COMMENT;
  471. head = limit; // do a readLine() on next call in here.
  472. goto exit;
  473. }
  474. else
  475. goto L_read;
  476. }
  477. }
  478. else
  479. {
  480. // skip leading whitespace
  481. while( cur<limit && isSpace( *cur ) )
  482. ++cur;
  483. }
  484. if( cur >= limit )
  485. goto L_read;
  486. if( *cur == '(' )
  487. {
  488. curText = *cur;
  489. curTok = DSN_LEFT;
  490. head = cur+1;
  491. goto exit;
  492. }
  493. if( *cur == ')' )
  494. {
  495. curText = *cur;
  496. curTok = DSN_RIGHT;
  497. head = cur+1;
  498. goto exit;
  499. }
  500. // Non-specctraMode, understands and deciphers escaped \, \r, \n, and \".
  501. // Strips off leading and trailing double quotes
  502. if( !specctraMode )
  503. {
  504. // a quoted string, will return DSN_STRING
  505. if( *cur == stringDelimiter )
  506. {
  507. // copy the token, character by character so we can remove doubled up quotes.
  508. curText.clear();
  509. ++cur; // skip over the leading delimiter, which is always " in non-specctraMode
  510. head = cur;
  511. while( head<limit )
  512. {
  513. // ESCAPE SEQUENCES:
  514. if( *head =='\\' )
  515. {
  516. char tbuf[8];
  517. char c;
  518. int i;
  519. if( ++head >= limit )
  520. break; // throw exception at L_unterminated
  521. switch( *head++ )
  522. {
  523. case '"':
  524. case '\\': c = head[-1]; break;
  525. case 'a': c = '\x07'; break;
  526. case 'b': c = '\x08'; break;
  527. case 'f': c = '\x0c'; break;
  528. case 'n': c = '\n'; break;
  529. case 'r': c = '\r'; break;
  530. case 't': c = '\x09'; break;
  531. case 'v': c = '\x0b'; break;
  532. case 'x': // 1 or 2 byte hex escape sequence
  533. for( i=0; i<2; ++i )
  534. {
  535. if( !isxdigit( head[i] ) )
  536. break;
  537. tbuf[i] = head[i];
  538. }
  539. tbuf[i] = '\0';
  540. if( i > 0 )
  541. c = (char) strtoul( tbuf, NULL, 16 );
  542. else
  543. c = 'x'; // a goofed hex escape sequence, interpret as 'x'
  544. head += i;
  545. break;
  546. default: // 1-3 byte octal escape sequence
  547. --head;
  548. for( i=0; i<3; ++i )
  549. {
  550. if( head[i] < '0' || head[i] > '7' )
  551. break;
  552. tbuf[i] = head[i];
  553. }
  554. tbuf[i] = '\0';
  555. if( i > 0 )
  556. c = (char) strtoul( tbuf, NULL, 8 );
  557. else
  558. c = '\\'; // a goofed octal escape sequence, interpret as '\'
  559. head += i;
  560. break;
  561. }
  562. curText += c;
  563. }
  564. else if( *head == '"' ) // end of the non-specctraMode DSN_STRING
  565. {
  566. curTok = DSN_STRING;
  567. ++head; // omit this trailing double quote
  568. goto exit;
  569. }
  570. else
  571. curText += *head++;
  572. } // while
  573. // L_unterminated:
  574. wxString errtxt( _( "Un-terminated delimited string" ) );
  575. THROW_PARSE_ERROR( errtxt, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  576. }
  577. }
  578. else // is specctraMode, tests in this block should not occur in KiCad mode.
  579. {
  580. /* get the dash out of a <pin_reference> which is embedded for example
  581. like: U2-14 or "U2"-"14"
  582. This is detectable by a non-space immediately preceeding the dash.
  583. */
  584. if( *cur == '-' && cur>start && !isSpace( cur[-1] ) )
  585. {
  586. curText = '-';
  587. curTok = DSN_DASH;
  588. head = cur+1;
  589. goto exit;
  590. }
  591. // switching the string_quote character
  592. if( prevTok == DSN_STRING_QUOTE )
  593. {
  594. static const wxString errtxt( _("String delimiter must be a single character of ', \", or $"));
  595. char cc = *cur;
  596. switch( cc )
  597. {
  598. case '\'':
  599. case '$':
  600. case '"':
  601. break;
  602. default:
  603. THROW_PARSE_ERROR( errtxt, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  604. }
  605. curText = cc;
  606. head = cur+1;
  607. if( head<limit && !isSep( *head ) )
  608. {
  609. THROW_PARSE_ERROR( errtxt, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  610. }
  611. curTok = DSN_QUOTE_DEF;
  612. goto exit;
  613. }
  614. // specctraMode DSN_STRING
  615. if( *cur == stringDelimiter )
  616. {
  617. ++cur; // skip over the leading delimiter: ",', or $
  618. head = cur;
  619. while( head<limit && !isStringTerminator( *head ) )
  620. ++head;
  621. if( head >= limit )
  622. {
  623. wxString errtxt( _( "Un-terminated delimited string" ) );
  624. THROW_PARSE_ERROR( errtxt, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  625. }
  626. curText.clear();
  627. curText.append( cur, head );
  628. ++head; // skip over the trailing delimiter
  629. curTok = DSN_STRING;
  630. goto exit;
  631. }
  632. } // specctraMode
  633. // non-quoted token, read it into curText.
  634. curText.clear();
  635. head = cur;
  636. while( head<limit && !isSep( *head ) )
  637. curText += *head++;
  638. if( isNumber( curText.c_str(), curText.c_str() + curText.size() ) )
  639. {
  640. curTok = DSN_NUMBER;
  641. goto exit;
  642. }
  643. if( specctraMode && curText == "string_quote" )
  644. {
  645. curTok = DSN_STRING_QUOTE;
  646. goto exit;
  647. }
  648. curTok = findToken( curText );
  649. exit: // single point of exit, no returns elsewhere please.
  650. curOffset = cur - start;
  651. next = head;
  652. // printf("tok:\"%s\"\n", curText.c_str() );
  653. return curTok;
  654. }
  655. wxArrayString* DSNLEXER::ReadCommentLines()
  656. {
  657. wxArrayString* ret = 0;
  658. bool cmt_setting = SetCommentsAreTokens( true );
  659. int tok = NextTok();
  660. if( tok == DSN_COMMENT )
  661. {
  662. ret = new wxArrayString();
  663. do
  664. {
  665. ret->Add( FromUTF8() );
  666. }
  667. while( ( tok = NextTok() ) == DSN_COMMENT );
  668. }
  669. SetCommentsAreTokens( cmt_setting );
  670. return ret;
  671. }