Debian Codegraph @

src/core/chuck_compile.cpp

raw symbols SCIP
1 /*----------------------------------------------------------------------------
2 ChucK Strongly-timed Audio Programming Language
3 Compiler, Virtual Machine, and Synthesis Engine
4
5 Copyright (c) 2003 Ge Wang and Perry R. Cook. All rights reserved.
6 http://chuck.stanford.edu/
7 http://chuck.cs.princeton.edu/
8
9 This program is free software; you can redistribute it and/or modify
10 it under the dual-license terms of EITHER the MIT License OR the GNU
11 General Public License (the latter as published by the Free Software
12 Foundation; either version 2 of the License or, at your option, any
13 later version).
14
15 This program is distributed in the hope that it will be useful and/or
16 interesting, but WITHOUT ANY WARRANTY; without even the implied warranty
17 of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 MIT Licence and/or the GNU General Public License for details.
19
20 You should have received a copy of the MIT License and the GNU General
21 Public License (GPL) along with this program; a copy of the GPL can also
22 be obtained by writing to the Free Software Foundation, Inc., 59 Temple
23 Place, Suite 330, Boston, MA 02111-1307 U.S.A.
24 -----------------------------------------------------------------------------*/
25
26 //-----------------------------------------------------------------------------
27 // file: chuck_compile.cpp
28 // desc: chuck compile system unifying parser, type checker, and emitter
29 //
30 // author: Ge Wang ([email protected] | [email protected])
31 // date: (see header for information)
32 //-----------------------------------------------------------------------------
33 #include "chuck_compile.h"
34 #include "chuck_lang.h"
35 #include "chuck_errmsg.h"
36 #include "chuck.h"
37 #include "chuck_io.h"
38
39 #ifndef __DISABLE_OTF_SERVER__
40 #include "chuck_otf.h"
41 #endif
42
43 #include "ugen_osc.h"
44 #include "ugen_xxx.h"
45 #include "ugen_filter.h"
46 #include "ugen_stk.h"
47 #include "uana_xform.h"
48 #include "uana_extract.h"
49
50 #include "ulib_ai.h"
51 #include "ulib_doc.h"
52 #include "ulib_machine.h"
53 #include "ulib_math.h"
54 #include "util_platforms.h"
55 #include "ulib_std.h"
56 #include "util_string.h"
57
58 #ifndef __DISABLE_NETWORK__
59 #include "ulib_opsc.h"
60 #endif
61
62 #if defined(__PLATFORM_WINDOWS__)
63 #include "dirent_win32.h"
64 #endif
65
66 #include <sys/stat.h>
67
68 #include <string>
69 #include <vector>
70 #include <algorithm>
71 #include <set>
72 using namespace std;
73
74
75
76
77 //-----------------------------------------------------------------------------
78 // function prototypes
79 //-----------------------------------------------------------------------------
80 t_CKBOOL load_internal_modules( Chuck_Compiler * compiler );
81 t_CKBOOL load_external_modules( Chuck_Compiler * compiler,
82 const char * extension,
83 list<string> & chugin_search_paths,
84 list<string> & named_dls);
85 t_CKBOOL load_module( Chuck_Compiler * compiler, Chuck_Env * env,
86 f_ck_query query, const char * name, const char * nspc );
87
88
89
90
91 //-----------------------------------------------------------------------------
92 // name: Chuck_Compiler()
93 // desc: constructor
94 //-----------------------------------------------------------------------------
95 Chuck_Compiler::Chuck_Compiler()
96 {
97 emitter = NULL;
98 code = NULL;
99
100 // REFACTOR-2017: add carrier
101 m_carrier = NULL;
102 // initialize
103 m_auto_depend = FALSE;
104
105 // origin hint | 1.5.0.0 (ge) added
106 m_originHint = ckte_origin_UNKNOWN;
107 }
108
109
110
111
112 //-----------------------------------------------------------------------------
113 // name: ~Chuck_Compiler()
114 // desc: destructor
115 //-----------------------------------------------------------------------------
116 Chuck_Compiler::~Chuck_Compiler()
117 {
118 // call shutdown
119 this->shutdown();
120 }
121
122
123
124
125 //-----------------------------------------------------------------------------
126 // name: initialize()
127 // desc: initialize the compiler
128 //-----------------------------------------------------------------------------
129 t_CKBOOL Chuck_Compiler::initialize()
130 {
131 // this should have been set by initialization
132 assert( m_carrier != NULL );
133
134 // set origin hint
135 m_originHint = ckte_origin_BUILTIN;
136
137 // allocate the type checker
138 if( !type_engine_init( m_carrier ) )
139 goto error;
140 // ensure carrier's env is set in type_engine_init
141 assert( m_carrier->env != NULL );
142
143 // allocate the emitter
144 emitter = emit_engine_init( m_carrier->env );
145 // add reference
146 CK_SAFE_ADD_REF( emitter );
147 // set auto depend to 0
148 m_auto_depend = FALSE;
149
150 // load internal libs
151 if( !load_internal_modules( this ) )
152 goto error;
153
154 // unset origin hint
155 m_originHint = ckte_origin_UNKNOWN;
156
157 return TRUE;
158
159 error:
160 // clean up | 1.4.1.0 (ge) removed -- should be cleaned up outside
161 // this->shutdown();
162
163 // pop indent
164 EM_poplog();
165
166 return FALSE;
167 }
168
169
170
171
172 //-----------------------------------------------------------------------------
173 // name: shutdown()
174 // desc: shutdown the compiler
175 //-----------------------------------------------------------------------------
176 void Chuck_Compiler::shutdown()
177 {
178 // log
179 EM_log( CK_LOG_SYSTEM, "shutting down compiler..." ) ;
180 // push indent
181 EM_pushlog();
182
183 // free emitter (and set emitter to NULL)
184 emit_engine_shutdown( emitter );
185 // check the pointer is now NULL
186 assert( emitter == NULL );
187
188 // clear more state
189 code = NULL;
190 m_auto_depend = FALSE;
191 m_recent.clear();
192
193 // log | 1.5.1.8
194 EM_log( CK_LOG_SYSTEM, "compiler shutown complete." ) ;
195 // pop indent
196 EM_poplog();
197
198 // if we have carrier
199 if( m_carrier != NULL )
200 {
201 // free type engine env within carrier
202 type_engine_shutdown( m_carrier );
203 // check the pointer is now NULL
204 assert( m_carrier->env == NULL );
205 // zero out the carrier reference | 1.5.1.1
206 m_carrier = NULL;
207 }
208 }
209
210
211
212
213 //-----------------------------------------------------------------------------
214 // name: compileFile()
215 // desc: parse, type-check, and emit a program from file
216 //-----------------------------------------------------------------------------
217 t_CKBOOL Chuck_Compiler::compileFile( const string & filename )
218 {
219 // call internal compile file with option
220 return this->compile_file_opt( filename, te_do_all );
221 }
222
223
224
225
226 //-----------------------------------------------------------------------------
227 // name: compileCode()
228 // desc: parse, type-check, and emit a program from code
229 //-----------------------------------------------------------------------------
230 t_CKBOOL Chuck_Compiler::compileCode( const string & codeLiteral,
231 const string & optFilepath )
232 {
233 // call internal compile file with option
234 return this->compile_code_opt( codeLiteral, optFilepath, te_do_all );
235 }
236
237
238
239
240 //-----------------------------------------------------------------------------
241 // name: importFile()
242 // desc: import a CK file, observing the semantics of chuck @import
243 //-----------------------------------------------------------------------------
244 t_CKBOOL Chuck_Compiler::importFile( const string & filename )
245 {
246 // call internal compile file with option
247 return this->compile_file_opt( filename, te_do_import_only );
248 }
249
250
251
252
253 //-----------------------------------------------------------------------------
254 // name: importCode()
255 // desc: import from code, observing the semantics of chuck @import
256 //-----------------------------------------------------------------------------
257 t_CKBOOL Chuck_Compiler::importCode( const string & codeLiteral,
258 const string & optFilepath )
259 {
260 // call internal compile file with option
261 return this->compile_code_opt( codeLiteral, optFilepath, te_do_import_only );
262 }
263
264
265
266
267 //-----------------------------------------------------------------------------
268 // name: importChugin()
269 // desc: import a chugin by path (and optional short-hand name)
270 //-----------------------------------------------------------------------------
271 t_CKBOOL Chuck_Compiler::importChugin( const string & path,
272 t_CKBOOL createNamespace,
273 const string & name,
274 string & errorStr )
275 {
276 // check if chugin of same name (regardless of path)
277 // has already been loaded | 1.5.5.8 (ge) added
278 if( m_importRegistry.isChuginLoaded( path ) )
279 {
280 // print `[chugin] X.chug`
281 logChuginLoad( name, CK_LOG_HERALD );
282 // print `[SKIP]`
283 EM_log_opts( CK_LOG_HERALD, EM_LOG_NO_PREFIX, "[%s]", TC::orange("SKIP",true).c_str() );
284 // print reason
285 EM_log( CK_LOG_HERALD, " |- (chugin of same name already imported)" );
286 // done
287 return FALSE;
288 }
289
290 // check if this import should be in its namespace | 1.5.4.0 (ge) added
291 if( createNamespace )
292 {
293 // make context for this chugin import and load it
294 // this is necessary to make sure the chugin is imported into its own
295 // namespace, to avoid being imported into say a host namespace -- e.g.,
296 // a chuck file that @import this chugin
297 // ALSO: if the chuck file that imports the chugin contains an error,
298 // its context would be cleaned up, which leads to a crash on chuck exit;
299 // this created context prevent that crash
300 // ... further investigation may be beneficial to fully understand this
301 // mechanism
302 type_engine_load_context( this->carrier()->env, type_engine_make_context( NULL, "@[chugin-import]" ) );
303 }
304
305 // call internal import chugin
306 t_CKBOOL ret = this->import_chugin_opt( path, name, errorStr );
307
308 // if create namespace
309 if( createNamespace )
310 {
311 // unload the context
312 type_engine_unload_context( this->carrier()->env );
313 }
314
315 // done
316 return ret;
317 }
318
319
320
321
322 //-----------------------------------------------------------------------------
323 // name: compile_file_opt()
324 // desc: parse, type-check, and emit a program, with option for how much to compile
325 //-----------------------------------------------------------------------------
326 t_CKBOOL Chuck_Compiler::compile_file_opt( const string & filename, te_HowMuch extent )
327 {
328 // create a compile target
329 Chuck_CompileTarget * target = new Chuck_CompileTarget( extent );
330 // resolve filename locally
331 if( !this->openFile( target, filename, NULL, FALSE ) )
332 {
333 // delete target
334 CK_SAFE_DELETE( target );
335 // return
336 return FALSE;
337 }
338
339 // compile target; compile() will memory-manage target (so no need to delete here)
340 return this->compile( target );
341 }
342
343
344
345
346 //-----------------------------------------------------------------------------
347 // name: compile_code_opt()
348 // desc: parse, type-check, and emit a program, with options for filepath
349 // and for how much to compile
350 //-----------------------------------------------------------------------------
351 t_CKBOOL Chuck_Compiler::compile_code_opt( const string & codeLiteral,
352 const string & optFilepath,
353 te_HowMuch extent )
354 {
355 // create a compile target
356 Chuck_CompileTarget * target = new Chuck_CompileTarget( extent );
357 // set filename to code literal constant
358 target->filename = CHUCK_CODE_LITERAL_SIGNIFIER;
359 // check for optional filename
360 string opt = trim(optFilepath);
361 // the path base (e.g., for import path)
362 string pathBase;
363 // is it empty?
364 if( opt == "" )
365 {
366 // get working directory
367 pathBase = this->carrier()->chuck->getParamString( CHUCK_PARAM_WORKING_DIRECTORY );
368 }
369 else // not empty
370 {
371 // use the optionally provided path, make into full path if not already
372 opt = normalize_filepath_append_ck( opt );
373 // get the path portion of the optionally provide path
374 pathBase = extract_filepath_dir( opt );
375 }
376 // construct full path to be associated with the file so me.sourceDir() works
377 target->absolutePath = pathBase + target->filename;
378 // set code literal
379 target->codeLiteral = codeLiteral;
380
381 // compile target; compile() will memory-manage target (so no need to delete here)
382 return this->compile( target );
383 }
384
385
386
387
388 //-----------------------------------------------------------------------------
389 // name: compile()
390 // desc: compile a single target
391 //-----------------------------------------------------------------------------
392 t_CKBOOL Chuck_Compiler::compile( Chuck_CompileTarget * target )
393 {
394 // hold return value
395 t_CKBOOL ret = TRUE;
396 // compilation sequence
397 std::vector<ImportTargetNode *> sequence;
398 // if cycle encountered, this returns cycle path
399 std::vector<ImportTargetNode *> problems;
400 // local import target node
401 ImportTargetNode node( target, 0, 0 );
402
403 // set the chuck
404 target->the_chuck = this->carrier()->chuck;
405 // clear in-progress
406 this->imports()->clearInProgress();
407 // add current target to registry to avoid cycles
408 this->imports()->addInProgress( target );
409 // scan for imports
410 if( !this->scan_imports( target ) )
411 {
412 // error encountered
413 ret = FALSE;
414 // clean up
415 goto cleanup;
416 }
417
418 // topological sort for serial compilation
419 if( !this->generate_compile_sequence( &node, sequence, problems ) )
420 {
421 // cycle detected
422 EM_error2( 0, "@import error -- cycle detected:" );
423 // print head of cycle
424 EM_error2( 0, " |- '%s' is imported from...", problems[0]->target->filename.c_str() );
425 for( t_CKINT i = 1; i < problems.size()-1; i++ )
426 {
427 // print middle of cycle
428 EM_error2( 0, " |- '%s':[line %d], which is imported from...", problems[i]->target->filename.c_str(), problems[i-1]->line );
429 // log for more detail
430 EM_log_opts( CK_LOG_INFO, EM_LOG_NO_PREFIX, "[chuck]: |- (full path: '%s')", problems[i]->target->absolutePath.c_str() );
431 }
432 // print origin of cycle
433 EM_error2( 0, " |- '%s':[line %d] (this is the originating file)", problems.back()->target->filename.c_str(), problems[problems.size()-2]->line );
434 // error encountered
435 ret = FALSE;
436 // clean up
437 goto cleanup;
438 }
439
440 // iterator over sequence
441 // NOTE: the base target should be the last one in the sequence
442 for( t_CKINT i = 0; i < sequence.size(); i++ )
443 {
444 // log
445 EM_log( CK_LOG_FINER, "compiling import target '%s'...", target->filename.c_str() );
446
447 // compile dependency (import only)
448 ret = compile_single( sequence[i]->target );
449 if( !ret )
450 {
451 // if there is a container
452 if( sequence[i]->target->howMuch == te_do_import_only && sequence[i]->target != target )
453 {
454 // set target for printing filename where error is
455 EM_setCurrentTarget( sequence[i]->target );
456 EM_error2( 0, "...in file '%s'", sequence[i]->target->absolutePath.c_str() );
457 // set target for error reporting for the originating file
458 EM_setCurrentTarget( target );
459 // report container
460 EM_error2( 0, "(error originates in an imported file that '%s' depends on...", target->filename.c_str() );
461 EM_error2( 0, "...i.e., '%s' directly or indirectly imports '%s')", target->filename.c_str(), sequence[i]->target->filename.c_str() );
462 // unset target
463 EM_setCurrentTarget( NULL );
464 }
465 // error encountered
466 ret = FALSE;
467 // clean up
468 goto cleanup;
469 }
470
471 // if target was an import (i.e., don't do this with the base target)
472 if( sequence[i]->target->howMuch == te_do_import_only )
473 {
474 // move target from in-progress to imported in registry
475 this->imports()->commit( sequence[i]->target );
476 }
477 }
478
479 cleanup:
480 // 1.4.1.0 (ge) | added to unset the fileName reference, which determines
481 // how messages print to console (e.g., [file.ck]: or [chuck]:)
482 // 1.5.0.5 (ge) | changed to reset_parse() which does more reset
483 // reset the parser, including reset filename and unset current chuck *
484 reset_parse();
485
486 // clear the in-progress list; should include the original target
487 this->imports()->clearInProgress();
488
489 return ret;
490 }
491
492
493
494
495 //-----------------------------------------------------------------------------
496 // name: generate_compile_sequence()
497 // desc: produce a compilation sequences of targets from a import dependency graph
498 //-----------------------------------------------------------------------------
499 t_CKBOOL Chuck_Compiler::generate_compile_sequence( ImportTargetNode * head,
500 std::vector<ImportTargetNode *> & sequence,
501 std::vector<ImportTargetNode *> & problems )
502 {
503 // clear return vector
504 sequence.clear();
505
506 // sets of markings
507 std::vector<Chuck_CompileTarget *> v;
508 std::set<Chuck_CompileTarget *> permanent;
509 std::set<Chuck_CompileTarget *> temporary;
510
511 // topological sort
512 if( !visit( head, sequence, permanent, temporary, problems ) ) return FALSE;
513
514 // done
515 return TRUE;
516 }
517
518
519
520
521 //-----------------------------------------------------------------------------
522 // name: visit()
523 // desc: recursive componet of topological sort function
524 //-----------------------------------------------------------------------------
525 t_CKBOOL Chuck_Compiler::visit( ImportTargetNode * node,
526 std::vector<ImportTargetNode *> & sequence,
527 std::set<Chuck_CompileTarget *> & permanent,
528 std::set<Chuck_CompileTarget *> & temporary,
529 std::vector<ImportTargetNode *> & problems )
530 {
531 // cycle
532 t_CKBOOL acyclic = TRUE;
533 // the target
534 Chuck_CompileTarget * target = node->target;
535
536 // if node already complete, can safely ignore
537 if( target->state == te_compile_complete ) return TRUE;
538 // is node marked permanent?
539 if( permanent.find(target) != permanent.end() ) return TRUE;
540 // is node marked temporary? if so, CYCLE detected
541 if( temporary.find(target) != temporary.end() )
542 { problems.push_back(node); return FALSE; }
543
544 // add node to temporary
545 temporary.insert(target);
546
547 // loop over dependencies
548 for( t_CKINT i = 0; i < target->dependencies.size(); i++ )
549 {
550 // visit dependency
551 acyclic = visit( &(target->dependencies[i]), sequence, permanent, temporary, problems );
552 // if cycle detected
553 if( !acyclic )
554 { problems.push_back(node); return FALSE; }
555 }
556
557 // add
558 permanent.insert(target);
559 // append node (should be prepend, but we will reverse later)
560 sequence.push_back(node);
561
562 return TRUE;
563 }
564
565
566
567
568 //-----------------------------------------------------------------------------
569 // name: matchFilename()
570 // desc: test for filename match; if 'ext' is empty, will test with extensions
571 // this function updates 'filename' with the first match
572 //-----------------------------------------------------------------------------
573 static t_CKBOOL matchFilename( std::string & filename,
574 const std::string & ext,
575 const std::vector<std::string> & extensions )
576 {
577 // test filename as is
578 if( ck_fileexists( filename ) && !ck_isdir( filename ) ) return TRUE;
579
580 // if no extension
581 if( ext == "" )
582 {
583 // go over the extensions
584 for( t_CKINT i = 0; i < extensions.size(); i++ )
585 {
586 // concat
587 string f = filename + extensions[i];
588 // test for match
589 if( ck_fileexists(f) && !ck_isdir( f ) )
590 {
591 // set
592 filename = f;
593 // done
594 return TRUE;
595 }
596 }
597 }
598 // if no match and has .chug extension
599 else if( ext == ".chug" )
600 {
601 // try appending .wasm
602 string f = filename + ".wasm";
603 // test for match
604 if( ck_fileexists(f) && !ck_isdir( f ) )
605 {
606 // set
607 filename = f;
608 // done
609 return TRUE;
610 }
611 }
612
613 // no match
614 return FALSE;
615 }
616
617
618
619
620 //-----------------------------------------------------------------------------
621 // name: resolveFilename()
622 // desc: resolve filename into an absolutePath (see header file for more desc)
623 //-----------------------------------------------------------------------------
624 std::string Chuck_Compiler::resolveFilename( const std::string & filename,
625 const std::string & importerAbsolutePath,
626 t_CKBOOL expandSearchToGlobal )
627 {
628 // return value
629 string absolutePath = "";
630 // trim, expand, normalize to single /
631 string fname = normalize_directory_separator(expand_filepath(trim(filename)));
632 // whether fname is already an absolute path
633 t_CKBOOL isAlreadyAbsolutePath = is_absolute_path( fname );
634 // current extension, e.g., ".ck" ".chug" ".chug.wasm"
635 string extension = tolower(extract_filepath_ext( fname ));
636 // extensions to test (if none is present)
637 vector<string> exts; exts.push_back(".ck"); exts.push_back(".chug"); exts.push_back(".chug.wasm");
638
639 // log
640 EM_log( CK_LOG_FINE, "resolving filename: '%s'", filename.c_str() );
641 EM_pushlog();
642 EM_log( CK_LOG_FINE, "importer: '%s'", importerAbsolutePath.c_str() );
643 EM_log( CK_LOG_FINE, "expand-search: %s", expandSearchToGlobal ? "YES" : "NO" );
644 EM_poplog();
645
646 // check if already absolute path
647 if( isAlreadyAbsolutePath )
648 {
649 // if already absolute path, do not expand search
650 expandSearchToGlobal = FALSE;
651 // tentative set as filename to open
652 absolutePath = fname;
653 }
654 else // not already absolute path, create tentative absolute path
655 {
656 // if this is part of an @import
657 if( importerAbsolutePath != "" )
658 {
659 // the importer is a file; transplant filename
660 absolutePath = transplant_filepath( importerAbsolutePath, fname );
661 }
662 else // otherwise, construct path from working directory
663 {
664 // use current working directory
665 absolutePath = carrier()->chuck->getParamString(CHUCK_PARAM_WORKING_DIRECTORY) + fname;
666 }
667 }
668
669 // filter through realpath | 1.5.4.5 (ge & nshaheed)
670 // NOTE: this ensures consistency, in case transplant_filepath() above normalizes file capitalization
671 absolutePath = normalize_filepath( absolutePath );
672
673 // protocol for filename resolution:
674 // |- test file existence + directory:
675 // |- use filename as is (e.g., "Foo.ck" or "Foo")
676 // |- failing that, try again with appended extensions
677 // |- if no current extension, try .ck, .chug, .chug.wasm
678 // |- if filename is .chug, try with .wasm
679 // |- if still no resolution at this point, and if expandSearchToGlobal,
680 // move to next directory in search path
681
682 // test for match
683 t_CKBOOL hasMatch = matchFilename( absolutePath, extension, exts );
684 // need for expanded search
685 if( !isAlreadyAbsolutePath && !hasMatch && expandSearchToGlobal )
686 {
687 // TODO: possible caching -- search for match first in registry
688 // match-right between each entry and fname; if found, return entry absolute path
689
690 // search paths: start with system paths
691 std::list<std::string> searchPaths = this->carrier()->chuck->getParamStringList( CHUCK_PARAM_IMPORT_PATH_SYSTEM );
692 // next, process packages paths (e.g., as managed by ChuMP)
693 std::list<std::string> packages_paths = this->carrier()->chuck->getParamStringList( CHUCK_PARAM_IMPORT_PATH_PACKAGES);
694 // append packages paths to search paths
695 append_path_list( searchPaths, packages_paths );
696 // iterate over packages paths | 1.5.4.1 (ge & nshaheed) added
697 for( std::list<std::string>::iterator it = packages_paths.begin(); it != packages_paths.end(); it++ )
698 {
699 // scan for subdirs, but only one-level in each packages path
700 scan_for_dirs_in_directory( *it, "", FALSE, searchPaths );
701 }
702 // finally, add user-managed search paths (no auto-load; all must be @imported)
703 append_path_list( searchPaths, this->carrier()->chuck->getParamStringList( CHUCK_PARAM_IMPORT_PATH_USER) );
704
705 // go over paths
706 for( list<string>::iterator it = searchPaths.begin(); it != searchPaths.end(); it++ )
707 {
708 // construct path; expand path again here in case search path has things like ~
709 // make sure to normalize_filepath on the directory itself before appending fname,
710 // FYI normalize_filepath() verifies presence of file, fname could be without extension e.g., @import "Foo"
711 absolutePath = normalize_filepath( expand_filepath(*it), TRUE ) + fname;
712 // try to match, by known extensions if none specified
713 hasMatch = matchFilename( absolutePath, extension, exts );
714 // log
715 EM_log( CK_LOG_FINER, "testing match: '%s' ('%s')", absolutePath.c_str(), hasMatch ? "yes" : "no" );
716 // if match found, break out
717 if( hasMatch ) break;
718 }
719
720 // filter through realpath, part 2 | 1.5.4.5 (ge & nshaheed)
721 // NOTE: this ensures consistency, in case transplant_filepath above normalizes file capitalization
722 absolutePath = normalize_filepath( absolutePath, FALSE );
723 }
724
725 // log
726 EM_pushlog();
727 if( hasMatch ) EM_log( CK_LOG_FINE, "resolved: '%s'", absolutePath.c_str() );
728 else EM_log( CK_LOG_FINE, "filename '%s' unresolved", filename.c_str() );
729 EM_poplog();
730
731 // return value
732 return hasMatch ? absolutePath : "";
733 }
734
735
736
737
738 //-----------------------------------------------------------------------------
739 // name: compile_entire_file()
740 // desc: scan, type-check, and emit a program
741 //-----------------------------------------------------------------------------
742 t_CKBOOL Chuck_Compiler::compile_entire_file( Chuck_Context * context )
743 {
744 // 0th-scan (pass 0)
745 if( !type_engine_scan0_prog( env(), context->parse_tree, te_do_all ) )
746 return FALSE;
747
748 // 1st-scan (pass 1)
749 if( !type_engine_scan1_prog( env(), context->parse_tree, te_do_all ) )
750 return FALSE;
751
752 // 2nd-scan (pass 2)
753 if( !type_engine_scan2_prog( env(), context->parse_tree, te_do_all ) )
754 return FALSE;
755
756 // check the program (pass 3)
757 if( !type_engine_check_context( env(), context, te_do_all ) )
758 return FALSE;
759
760 // emit (pass 4)
761 this->code = emit_engine_emit_prog( emitter, context->parse_tree, te_do_all );
762 if( !code ) return FALSE;
763
764 // set the state of the context to done
765 context->progress = Chuck_Context::P_ALL_DONE;
766
767 return TRUE;
768 }
769
770
771
772
773 //-----------------------------------------------------------------------------
774 // name: compile_import_only() | 1.5.4.0 (ge) added
775 // desc: import only public definitions (classes and operator overloads)
776 //-----------------------------------------------------------------------------
777 t_CKBOOL Chuck_Compiler::compile_import_only( Chuck_Context * context )
778 {
779 // set the state of the context to done
780 context->progress = Chuck_Context::P_IMPORTING;
781
782 // 0th-scan (pass 0)
783 if( !type_engine_scan0_prog( env(), context->parse_tree, te_do_import_only ) )
784 return FALSE;
785
786 // 1st-scan (pass 1)
787 if( !type_engine_scan1_prog( env(), context->parse_tree, te_do_import_only ) )
788 return FALSE;
789
790 // 2nd-scan (pass 2)
791 if( !type_engine_scan2_prog( env(), context->parse_tree, te_do_import_only ) )
792 return FALSE;
793
794 // check the program (pass 3)
795 if( !type_engine_check_context( env(), context, te_do_import_only ) )
796 return FALSE;
797
798 // emit (pass 4)
799 if( !emit_engine_emit_prog( emitter, context->parse_tree, te_do_import_only ) )
800 return FALSE;
801
802 // set the state of the context to done
803 context->progress = Chuck_Context::P_IMPORTED;
804
805 return TRUE;
806 }
807
808
809
810
811 //-----------------------------------------------------------------------------
812 // name: compile_all_except_import()
813 // desc: compile everything except public definitions
814 //-----------------------------------------------------------------------------
815 t_CKBOOL Chuck_Compiler::compile_all_except_import( Chuck_Context * context )
816 {
817 // 0th scan only deals with classes, so is not needed
818
819 // 1st-scan (pass 1)
820 if( !type_engine_scan1_prog( env(), context->parse_tree, te_skip_import ) )
821 return FALSE;
822
823 // 2nd-scan (pass 2)
824 if( !type_engine_scan2_prog( env(), context->parse_tree, te_skip_import ) )
825 return FALSE;
826
827 // check the program (pass 3)
828 if( !type_engine_check_context( env(), context, te_skip_import ) )
829 return FALSE;
830
831 // emit (pass 4)
832 code = emit_engine_emit_prog( emitter, context->parse_tree, te_skip_import );
833 if( !code ) return FALSE;
834
835 // set the state of the context to done
836 context->progress = Chuck_Context::P_ALL_DONE;
837
838 return TRUE;
839 }
840
841
842
843
844 //-----------------------------------------------------------------------------
845 // name: type_engine_scan_import()
846 // desc: scan for a list of imports
847 //-----------------------------------------------------------------------------
848 t_CKBOOL type_engine_scan_import( Chuck_Env * env, a_Stmt_List stmt_list,
849 Chuck_CompileTarget * target,
850 Chuck_Compiler * compiler )
851 {
852 // type check the stmt_list
853 while( stmt_list )
854 {
855 // the current statement
856 if( stmt_list->stmt && stmt_list->stmt->s_type == ae_stmt_import )
857 {
858 // get the import list
859 a_Import importList = stmt_list->stmt->stmt_import.list;
860 // loop over import list
861 while( importList )
862 {
863 // resolve, using importer's absolute path, expandSearch == TRUE
864 string abs = compiler->resolveFilename( importList->what, target->absolutePath, TRUE );
865 // if cannot resolve filename
866 if( abs == "" )
867 {
868 // print error
869 EM_error2( importList->where, "no such file: '%s'", importList->what );
870 // done
871 return FALSE;
872 }
873
874 // lookup to see there is already a target
875 Chuck_CompileTarget * t = compiler->imports()->lookup( abs, target );
876 if( !t )
877 {
878 // the filename (without full path)
879 string theFile = extract_filepath_file(abs);
880 // get extension
881 string ext = tolower(extract_filepath_ext(abs));
882 // error string for reporting, in case of error
883 string errorStr;
884 // test extension
885 if( ext == ".chug" || ext == ".wasm" )
886 {
887 // load the chugin, in its own namespace == TRUE
888 if( !compiler->importChugin( abs, TRUE, theFile, errorStr ) )
889 {
890 // print error (chugin loading only prints to log)
891 EM_error2( importList->where, "cannot load chugin: '%s'...", theFile.c_str() );
892 EM_error2( 0, "...(reason) %s", errorStr.length() ? errorStr.c_str() : "[none provided, unhelpfully (try running with more verbose log-level)]" );
893 EM_error2( 0, "...in file '%s'", abs.c_str() );
894 // error encountered in chugin load, bailing out
895 return FALSE;
896 }
897
898 // get the target
899 t = compiler->imports()->lookup( abs, target );
900 // check
901 if( !t )
902 {
903 // print error (chugin loading only prints to log)
904 EM_error2( 0, "(internal error) cannot locate imported chugin..." );
905 EM_error2( 0, " |- location: '%s'", abs.c_str() );
906 // error encountered in chugin load, bailing out
907 return FALSE;
908 }
909 }
910 else
911 {
912 // make new target with import only
913 t = new Chuck_CompileTarget( te_do_import_only );
914 // set filename, with transplant path, expand search if necessary
915 if( !compiler->openFile( t, importList->what, target, TRUE, importList->where ) )
916 {
917 // clean up
918 CK_SAFE_DELETE( t );
919 // error encountered, bailing out
920 return FALSE;
921 }
922 // add to registry's in-progress list
923 compiler->imports()->addInProgress( t );
924 }
925 }
926 // add to target
927 target->dependencies.push_back( ImportTargetNode( t, importList->where, importList->line ) );
928 // next in list
929 importList = importList->next;
930 }
931 }
932
933 // advance to the next statement
934 stmt_list = stmt_list->next;
935 }
936
937 return TRUE;
938 }
939
940
941
942
943 //-----------------------------------------------------------------------------
944 // name: type_engine_scan_import()
945 // desc: scan for a list of imports
946 //-----------------------------------------------------------------------------
947 t_CKBOOL type_engine_scan_import( Chuck_Env * env,
948 Chuck_CompileTarget * target,
949 Chuck_Compiler * compiler )
950 {
951 t_CKBOOL ret = TRUE;
952
953 // get AST
954 a_Program prog = target->AST;
955 if( !prog ) return FALSE;
956
957 // clear target dependencies
958 target->dependencies.clear();
959
960 // push indent
961 // EM_pushlog();
962
963 // go through each of the program sections
964 while( prog && ret )
965 {
966 switch( prog->section->s_type )
967 {
968 case ae_section_stmt:
969 // scan the statements
970 ret = type_engine_scan_import( env, prog->section->stmt_list, target, compiler );
971 break;
972
973 case ae_section_func:
974 break;
975
976 case ae_section_class:
977 break;
978
979 default:
980 EM_error2( prog->where,
981 "(internal error) unrecognized program section in type checker pre-scan..." );
982 ret = FALSE;
983 break;
984 }
985
986 // next section
987 prog = prog->next;
988 }
989
990 // pop indent
991 // EM_poplog();
992
993 return ret;
994 }
995
996
997
998
999 //-----------------------------------------------------------------------------
1000 // name: scan_imports()
1001 // desc: scan for @import statements; return a list of resulting import targets
1002 //-----------------------------------------------------------------------------
1003 t_CKBOOL Chuck_Compiler::scan_imports( Chuck_Env * env,
1004 Chuck_CompileTarget * target )
1005 {
1006 return type_engine_scan_import( env, target, this );
1007 }
1008
1009
1010
1011
1012 //-----------------------------------------------------------------------------
1013 // name: scan_imports()
1014 // desc: scan for imports
1015 //-----------------------------------------------------------------------------
1016 t_CKBOOL Chuck_Compiler::scan_imports( Chuck_CompileTarget * target )
1017 {
1018 // return value
1019 t_CKBOOL ret = TRUE;
1020
1021 // set as current target
1022 EM_setCurrentTarget( target );
1023
1024 // parse the code
1025 if( !chuck_parse( target ) )
1026 {
1027 // error encountered
1028 ret = FALSE;
1029 // clean up
1030 goto cleanup;
1031 }
1032
1033 // set the AST
1034 target->AST = g_program;
1035
1036 // log
1037 EM_log( CK_LOG_INFO, "@import scanning within target '%s'...", target->filename.c_str() );
1038
1039 // add the current file name to targets (to avoid duplicates/cycles)
1040 // scan for @import statements
1041 if( !scan_imports( env(), target ) )
1042 {
1043 // error encountered
1044 ret = FALSE;
1045 // bail out
1046 goto cleanup;
1047 }
1048
1049 // push log
1050 EM_pushlog();
1051 // loop over dependencies
1052 for( int i = 0; i < target->dependencies.size(); i++ )
1053 {
1054 // current dependency
1055 Chuck_CompileTarget * t = target->dependencies[i].target;
1056
1057 // check if the target has been successfully compiled already
1058 // (if so, we can assume that its dependencies has already been resolved)
1059 // (if not, scan for imports if it is not a chugin and does yet have an AST)
1060 if( t->state != te_compile_complete && t->chugin == NULL && t->AST == NULL )
1061 {
1062 // log
1063 EM_log( CK_LOG_FINE, "@import dependency found: '%s'", t->absolutePath.c_str() );
1064 // parse for scan import on imported file
1065 if( !scan_imports( t ) )
1066 {
1067 // error encountered
1068 ret = FALSE;
1069 // bail out; break here to make sure poplog() is run
1070 break;
1071 }
1072 }
1073 }
1074 // pop log
1075 EM_poplog();
1076
1077 cleanup:
1078 // null current target
1079 EM_setCurrentTarget( NULL );
1080
1081 // done
1082 return ret;
1083 }
1084
1085
1086
1087
1088 //-----------------------------------------------------------------------------
1089 // name: compile_single()
1090 // desc: scan, type-check, emit a single target (post parse and post import)
1091 //-----------------------------------------------------------------------------
1092 t_CKBOOL Chuck_Compiler::compile_single( Chuck_CompileTarget * target )
1093 {
1094 t_CKBOOL ret = TRUE;
1095
1096 // clear any error messages
1097 EM_reset_msg();
1098 // make the target current in the parser
1099 EM_setCurrentTarget( target );
1100
1101 // make the context
1102 Chuck_Context * context = type_engine_make_context( target->AST, target->filename );
1103 if( !context ) return FALSE;
1104
1105 // remember full path (added 1.3.0.0)
1106 context->full_path = target->absolutePath;
1107
1108 // reset the env
1109 env()->reset();
1110
1111 // load the context
1112 if( !type_engine_load_context( env(), context ) )
1113 return FALSE;
1114
1115 // compile
1116 if( target->howMuch == te_do_all )
1117 {
1118 if( !compile_entire_file( context ) )
1119 { ret = FALSE; goto cleanup; }
1120 }
1121 else if( target->howMuch == te_do_import_only )
1122 {
1123 if( !compile_import_only( context ) )
1124 { ret = FALSE; goto cleanup; }
1125 }
1126 else if( target->howMuch == te_skip_import )
1127 {
1128 if( !compile_all_except_import( context ) )
1129 { ret = FALSE; goto cleanup; }
1130 }
1131
1132 cleanup:
1133
1134 // make the target current in the parser
1135 EM_setCurrentTarget( NULL );
1136
1137 // commit
1138 if( ret ) // 1.5.4.3 (ge) update to call commit_namespaces | was: env()->global()->commit();
1139 { env()->commit_namespaces(); }
1140 // or rollback
1141 else // 1.5.4.3 (ge) update to call commit_namespaces | was: env()->global()->rollback();
1142 { env()->rollback_namespaces(); }
1143
1144 // unload the context from the type-checker
1145 if( !type_engine_unload_context( env() ) )
1146 {
1147 EM_error2( 0, "(internal error) unloading context..." );
1148 return FALSE;
1149 }
1150
1151 return ret;
1152 }
1153
1154
1155
1156
1157 //-----------------------------------------------------------------------------
1158 // name: output()
1159 // desc: get the code generated by the last do()
1160 //-----------------------------------------------------------------------------
1161 Chuck_VM_Code * Chuck_Compiler::output()
1162 {
1163 return this->code;
1164 }
1165
1166
1167
1168
1169 //-----------------------------------------------------------------------------
1170 // name: setReplaceDac()
1171 // desc: tell the compiler whether dac should be replaced in scripts
1172 // with the name of an external UGen, and if so which one
1173 //-----------------------------------------------------------------------------
1174 void Chuck_Compiler::setReplaceDac( t_CKBOOL shouldReplaceDac,
1175 const string & replacement )
1176 {
1177 emitter->should_replace_dac = shouldReplaceDac;
1178 emitter->dac_replacement = replacement;
1179 }
1180
1181
1182
1183 //-----------------------------------------------------------------------------
1184 // name: bind()
1185 // desc: bind a new type system module, via query function
1186 //-----------------------------------------------------------------------------
1187 t_CKBOOL Chuck_Compiler::bind( f_ck_query query_func, const string & name,
1188 const string & nspc )
1189 {
1190 // log
1191 EM_log( CK_LOG_SYSTEM, "on-demand binding compiler module '%s'...",
1192 name.c_str() );
1193 // push indent level
1194 EM_pushlog();
1195
1196 // get env
1197 Chuck_Env * env = this->env();
1198 // make context
1199 Chuck_Context * context = type_engine_make_context(
1200 NULL, string("@[bind:") + name + string("]") );
1201 // reset env - not needed since we just created the env
1202 env->reset();
1203 // load it
1204 type_engine_load_context( env, context );
1205
1206 // do it
1207 if( !load_module( this, env, query_func, name.c_str(), nspc.c_str() ) ) goto error;
1208
1209 // clear context
1210 type_engine_unload_context( env );
1211
1212 // commit what is in the type checker at this point
1213 env->global()->commit();
1214
1215 // preserve all operator overloads currently in registry | added 1.5.5.8 (ben)
1216 env->op_registry.preserve();
1217
1218 // pop indent level
1219 EM_poplog();
1220
1221 return TRUE;
1222
1223 error:
1224
1225 // probably dangerous: rollback
1226 env->global()->rollback();
1227
1228 // clear context
1229 type_engine_unload_context( env );
1230
1231 // pop indent level
1232 EM_poplog();
1233
1234 return FALSE;
1235 }
1236
1237
1238
1239
1240 //-----------------------------------------------------------------------------
1241 // name: load_module()
1242 // desc: load an internal module and add it to the type system
1243 //-----------------------------------------------------------------------------
1244 t_CKBOOL load_module( Chuck_Compiler * compiler, Chuck_Env * env, f_ck_query query,
1245 const char * name, const char * nspc )
1246 {
1247 Chuck_DLL * dll = NULL;
1248 t_CKBOOL query_failed = FALSE;
1249
1250 // create a DLL as a module (here DLL is not actually dynamically loaded
1251 // from disk, but rather is a construct that contains a query function
1252 dll = new Chuck_DLL( compiler->carrier(), name );
1253 // (fixed: 1.3.0.0) query_failed now catches either failure of load or query
1254 query_failed = !(dll->load( query ) && dll->query());
1255 // check and add contents to type system
1256 if( query_failed || !type_engine_add_dll( env, dll, nspc ) )
1257 {
1258 // print error
1259 EM_error2( 0, "internal error loading module '%s.%s'...", nspc, name );
1260 // print error if it came from DLL query
1261 if( query_failed ) { EM_error2( 0, "...(reason: %s)", dll->last_error() ); }
1262 // done
1263 return FALSE;
1264 }
1265
1266 // TODO: SAFE_DELETE( dll ) -- possibly in both error and success cases?
1267 return TRUE;
1268 }
1269
1270
1271
1272
1273 //-----------------------------------------------------------------------------
1274 // name: load_internal_modules()
1275 // desc: load internal base modules
1276 //-----------------------------------------------------------------------------
1277 t_CKBOOL load_internal_modules( Chuck_Compiler * compiler )
1278 {
1279 // log
1280 EM_log( CK_LOG_HERALD, "loading built-in modules..." );
1281 // push indent level
1282 EM_pushlog();
1283
1284 // get env
1285 Chuck_Env * env = compiler->env();
1286 // make context
1287 Chuck_Context * context = type_engine_make_context( NULL, "@[internal]" );
1288 // reset env - not needed since we just created the env
1289 env->reset();
1290 // load it
1291 type_engine_load_context( env, context );
1292
1293 // still compile MidiMsg even if __DISABLE_MIDI__
1294 if( !init_class_Midi( env ) ) goto error;
1295 #ifndef __DISABLE_MIDI__
1296 if( !init_class_MidiRW( env ) ) goto error;
1297 #endif // __DISABLE_MIDI__
1298
1299 // load
1300 EM_log( CK_LOG_HERALD, "module 'math'" );
1301 if( !load_module( compiler, env, libmath_query, "math", "global" ) ) goto error;
1302 EM_log( CK_LOG_HERALD, "module 'osc'" );
1303 load_module( compiler, env, osc_query, "osc", "global" );
1304 EM_log( CK_LOG_HERALD, "module 'ai'" );
1305 if( !load_module( compiler, env, libai_query, "ai", "global" ) ) goto error;
1306 EM_log( CK_LOG_HERALD, "module 'extract'" );
1307 load_module( compiler, env, extract_query, "extract", "global" );
1308 EM_log( CK_LOG_HERALD, "module 'filter'" );
1309 load_module( compiler, env, filter_query, "filter", "global" );
1310 EM_log( CK_LOG_HERALD, "module 'STK'" );
1311 load_module( compiler, env, stk_query, "stk", "global" );
1312 EM_log( CK_LOG_HERALD, "module 'xform'" );
1313 load_module( compiler, env, xform_query, "xform", "global" );
1314 EM_log( CK_LOG_HERALD, "module 'xxx'" );
1315 load_module( compiler, env, xxx_query, "xxx", "global" );
1316 EM_log( CK_LOG_HERALD, "module 'std'" );
1317 if( !load_module( compiler, env, libstd_query, "std", "global" ) ) goto error;
1318
1319 // load
1320 EM_log( CK_LOG_HERALD, "module 'machine'" );
1321 if( !load_module( compiler, env, machine_query, "machine", "global" ) ) goto error;
1322
1323 #ifndef __DISABLE_NETWORK__
1324 EM_log( CK_LOG_HERALD, "module 'opsc'" );
1325 if( !load_module( compiler, env, opensoundcontrol_query, "opsc", "global" ) ) goto error;
1326 #endif
1327
1328 // deprecated:
1329 // if( !load_module( compiler, env, net_query, "net", "global" ) ) goto error;
1330
1331 #ifndef __DISABLE_HID__
1332 EM_log( CK_LOG_HERALD, "module 'HID'" );
1333 if( !init_class_HID( env ) ) goto error;
1334 #endif
1335
1336 #ifndef __DISABLE_SERIAL__
1337 EM_log( CK_LOG_HERALD, "module 'SerialIO'" );
1338 if( !init_class_serialio( env ) ) goto error;
1339 #endif
1340
1341 EM_log( CK_LOG_HERALD, "module 'CKDoc'" );
1342 if( !load_module( compiler, env, ckdoc_query, "ckdoc", "global" ) ) goto error;
1343
1344 // clear context
1345 type_engine_unload_context( env );
1346
1347 // commit what is in the type checker at this point
1348 env->global()->commit();
1349
1350 // preserve all operator overloads currently in registry | 1.5.1.5
1351 env->op_registry.preserve();
1352
1353 // pop indent level
1354 EM_poplog();
1355
1356 return TRUE;
1357
1358 error:
1359 // probably dangerous: rollback
1360 env->global()->rollback();
1361
1362 // undo op registry entries | 1.5.1.5
1363 env->op_registry.reset2local();
1364
1365 // clear context
1366 type_engine_unload_context( env );
1367
1368 // pop indent level
1369 EM_poplog();
1370
1371 return FALSE;
1372 }
1373
1374
1375
1376
1377 //-----------------------------------------------------------------------------
1378 // name: getDirEntryAttribute()
1379 // desc: get directory entry attribute | 1.5.0.4 (ge) moved into function
1380 //-----------------------------------------------------------------------------
1381 t_CKBOOL getDirEntryAttribute( dirent * de, t_CKBOOL & isDirectory, t_CKBOOL & isRegular )
1382 {
1383 #if defined(__PLATFORM_WINDOWS__)
1384 isDirectory = de->data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
1385 isRegular = ((de->data.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) ||
1386 (de->data.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ||
1387 (de->data.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE));
1388 #elif defined(__WINDOWS_PTHREAD__) // Cygwin -- doesn't have dirent d_type
1389 string absolute_path = string(directory) + "/" + de->d_name;
1390 struct stat st;
1391 if( stat(absolute_path.c_str(), &st) == 0 )
1392 {
1393 isDirectory = st.st_mode & S_IFDIR;
1394 isRegular = st.st_mode & S_IFREG;
1395 }
1396 else
1397 {
1398 // uhh ...
1399 EM_log( CK_LOG_INFO,
1400 "unable to open file '%s', ignoring for chugins",
1401 absolute_path.c_str() );
1402 return false;
1403 }
1404 #else
1405 isDirectory = de->d_type == DT_DIR;
1406 isRegular = de->d_type == DT_REG;
1407 #endif
1408
1409 return true;
1410 }
1411
1412
1413
1414
1415 //-----------------------------------------------------------------------------
1416 // name: struct ChuginFileInfo()
1417 // desc: file info for loading
1418 //-----------------------------------------------------------------------------
1419 struct ChuginFileInfo
1420 {
1421 string filename;
1422 string path;
1423 bool isBundle;
1424
1425 // constructor
1426 ChuginFileInfo() { isBundle = false; }
1427
1428 // constructor
1429 ChuginFileInfo( const string & f, const string & p, bool bundle = false )
1430 {
1431 filename = f; path = p; isBundle = bundle;
1432 }
1433 };
1434 // compare function for sorting ChuginFileInfo
1435 static bool comp_func_chuginfileinfo( const ChuginFileInfo & a, const ChuginFileInfo & b )
1436 {
1437 return tolower( a.filename ) < tolower( b.filename );
1438 }
1439
1440
1441
1442
1443 //-----------------------------------------------------------------------------
1444 // name: format_dir_name_for_display()
1445 // desc: format directory name for display, considering underlying platform
1446 //-----------------------------------------------------------------------------
1447 static string format_dir_name_for_display( const string & path )
1448 {
1449 #ifndef __PLATFORM_WINDOWS__
1450 return path;
1451 #else // __PLATFORM_WINDOWS__
1452 return expand_filepath( path );
1453 #endif
1454 }
1455
1456
1457
1458 //-----------------------------------------------------------------------------
1459 // name: scan_external_modules_in_directory()
1460 // desc: scan all external modules by extension within a directory
1461 //-----------------------------------------------------------------------------
1462 t_CKBOOL scan_external_modules_in_directory( const string & directory,
1463 const string & extension,
1464 t_CKBOOL recursiveSearch,
1465 vector<ChuginFileInfo> & chugins2load,
1466 vector<string> & dirs2search,
1467 vector<string> & ckfiles2load )
1468 {
1469 // expand directory path
1470 string path = expand_filepath( directory, FALSE );
1471 // normalize path
1472 path = normalize_directory_name( path );
1473 // open the directory
1474 DIR * dir = opendir( path.c_str() );
1475
1476 // cannot open
1477 if( !dir ) return FALSE;
1478
1479 // while( (de = readdir(dir)) ) <- UE5 forces us to not do this
1480 // iterate over directory entries | 1.5.0.0 (ge + eito) #chunreal
1481 for( struct dirent * de = readdir( dir ); de != NULL; de = readdir(dir) )
1482 {
1483 t_CKBOOL is_regular = false;
1484 t_CKBOOL is_directory = false;
1485 // get attributes
1486 if( !getDirEntryAttribute( de, is_directory, is_regular ) ) continue;
1487
1488 // check | TODO: follow links?
1489 if( is_regular )
1490 {
1491 // check for ck files to pre-load
1492 if( extension_matches( de->d_name, ".ck" ) )
1493 {
1494 // construct absolute path
1495 string absolute_path = path + de->d_name;
1496 // append file path
1497 ckfiles2load.push_back( absolute_path );
1498 }
1499 // check extension passed in
1500 else if( extension_matches( de->d_name, extension ) )
1501 {
1502 // construct absolute path
1503 string absolute_path = path + de->d_name;
1504 // append module
1505 chugins2load.push_back( ChuginFileInfo( de->d_name, absolute_path ) );
1506 }
1507 }
1508 // recursive search? into directories...
1509 // (whose name doesn't end in .chug, unless it was precisely .chug)
1510 else if( recursiveSearch && is_directory && subdir_ok2recurse( de->d_name, extension ) )
1511 {
1512 // recurse | TODO: max depth?
1513 if( strncmp( de->d_name, ".", sizeof( "." ) ) != 0 &&
1514 strncmp( de->d_name, "..", sizeof( ".." ) ) != 0 )
1515 {
1516 // construct absolute path (use the non-expanded path for consistency when printing)
1517 string absolute_path = string(directory) + de->d_name;
1518 // queue search in sub-directory
1519 dirs2search.push_back( absolute_path );
1520 }
1521 }
1522 #ifdef __PLATFORM_APPLE__
1523 else if( is_directory && extension_matches( de->d_name, extension ) )
1524 {
1525 // On macOS, a chugin can either be a regular file (a .dylib simply renamed to .chug)
1526 // or it can be a MODULE like using CMake with add_library(FooChugin MODULE foo.cpp)
1527 // If it's a module bundle, then because .chug is a nonstandard extension,
1528 // on the filesystem it shows up as a directory ending in .chug.
1529 // If we see one of these directories, we can dive directly to the Contents/MacOS subfolder
1530 // and look for a regular file. | 1.5.0.1 (dbraun) added
1531 string absolute_path = path + "/" + de->d_name + "/Contents/MacOS";
1532 // probe NAME.chug/Contents/MacOS/NAME
1533 string actualName = extension_removed( de->d_name, extension );
1534 // construct
1535 absolute_path += "/" + actualName;
1536 // get cstr
1537 const char * subdirectory = absolute_path.c_str();
1538 // load directly
1539 chugins2load.push_back( ChuginFileInfo( de->d_name, subdirectory, true ) );
1540 }
1541 #endif // #ifdef __PLATFORM_APPLE__
1542 }
1543
1544 // close
1545 closedir( dir );
1546
1547 return TRUE;
1548 }
1549
1550
1551
1552
1553 //-----------------------------------------------------------------------------
1554 // name: scan_for_dirs_in_directory() | 1.5.4.1 (ge & nshaheed) added
1555 // desc: scan all subdirectories within a directory
1556 //-----------------------------------------------------------------------------
1557 t_CKBOOL scan_for_dirs_in_directory( const string & directory,
1558 const string & extensionForSubdirTest,
1559 t_CKBOOL recursiveSearch,
1560 list<string> & results )
1561 {
1562 // expand directory path
1563 string path = normalize_directory_name( expand_filepath( directory, FALSE ) );
1564 // open the directory
1565 DIR * dir = opendir( path.c_str() );
1566 // cannot open
1567 if( !dir ) return FALSE;
1568
1569 // local results
1570 list<string> localResults;
1571
1572 // while( (de = readdir(dir)) ) <- UE5 forces us to not do this
1573 // iterate over directory entries | 1.5.0.0 (ge + eito) #chunreal
1574 for( struct dirent * de = readdir(dir); de != NULL; de = readdir(dir) )
1575 {
1576 t_CKBOOL is_regularFile = false;
1577 t_CKBOOL is_directory = false;
1578 // get attributes
1579 if( !getDirEntryAttribute( de, is_directory, is_regularFile ) ) continue;
1580
1581 // check if directory
1582 if( is_directory )
1583 {
1584 // test for special cases (e.g., chugins that are directories)
1585 if( extensionForSubdirTest.length() && !subdir_ok2recurse( de->d_name, extensionForSubdirTest ) ) continue;
1586
1587 // check dir entry
1588 if( strncmp( de->d_name, ".", sizeof( "." ) ) != 0 &&
1589 strncmp( de->d_name, "..", sizeof( ".." ) ) != 0 )
1590 {
1591 // construct absolute path (use the non-expanded path for consistency when printing)
1592 string absolute_path = string(path) + de->d_name;
1593 // queue sub-directory
1594 localResults.push_back( normalize_directory_name(absolute_path) );
1595 }
1596 }
1597 }
1598
1599 // close
1600 closedir( dir );
1601
1602 // sort the local results
1603 localResults.sort();
1604 // copy local results
1605 append_path_list( results, localResults );
1606
1607 // recurse?
1608 if( recursiveSearch )
1609 {
1610 // iterate over local directoriesug
1611 for( list<string>::iterator it = localResults.begin(); it != localResults.end(); it++ )
1612 {
1613 // scan subdirs in this local dir
1614 scan_for_dirs_in_directory( *it, extensionForSubdirTest, recursiveSearch, results );
1615 }
1616 }
1617
1618 return TRUE;
1619 }
1620
1621
1622
1623
1624 //-----------------------------------------------------------------------------
1625 // name: logChuginLoad() | 1.5.2.5 (ge)
1626 // desc: local function quick-hand for logging a chugin load
1627 //-----------------------------------------------------------------------------
1628 void logChuginLoad( const string & name, t_CKINT logLevel )
1629 {
1630 // log with no newline; print `[chugin] X.chug`
1631 EM_log_opts( logLevel, EM_LOG_NO_NEWLINE, "[%s] %s ", TC::magenta("chugin",true).c_str(), name.c_str() );
1632 }
1633
1634
1635
1636
1637 //-----------------------------------------------------------------------------
1638 // name: logCKFileFound() | 1.5.4.1 (ge & nshaheed)
1639 // desc: local function quick-hand for logging a chuck file found
1640 //-----------------------------------------------------------------------------
1641 void logCKFileFound( const string & name, t_CKINT logLevel )
1642 {
1643 // log with no newline; print `[chuck file] X.ck`
1644 EM_log_opts( logLevel, EM_LOG_NO_NEWLINE, "[%s] %s ", TC::blue("chuck file",true).c_str(), name.c_str() );
1645
1646 // print success status
1647 EM_log_opts( logLevel, EM_LOG_NO_PREFIX, "[%s]", TC::green("FOUND",true).c_str() );
1648 }
1649
1650
1651
1652
1653 //-----------------------------------------------------------------------------
1654 // name: import_chugin_opt()
1655 // desc: load chugin module by path, with options
1656 //-----------------------------------------------------------------------------
1657 t_CKBOOL Chuck_Compiler::import_chugin_opt( const string & path, const string & name, string & errorStr )
1658 {
1659 // get env
1660 Chuck_Env * env = this->env();
1661
1662 // NOTE this (running with verbose >= 5) is more informative if the chugin crashes while loading, we can see the name
1663 EM_log( CK_LOG_INFO, "@import loading [chugin] %s...", name.c_str() );
1664 EM_log( CK_LOG_INFO, " |- path: '%s'", path.c_str() );
1665
1666 // create chuck DLL data structure
1667 Chuck_DLL * dll = new Chuck_DLL( this->carrier(), name != "" ? name.c_str() : (extract_filepath_file(path)).c_str() );
1668 t_CKBOOL query_failed = FALSE;
1669
1670 // clear error string
1671 errorStr = "";
1672
1673 // load (but don't query yet; lazy mode == TRUE)
1674 if( dll->load( path.c_str(), CK_QUERY_FUNC, TRUE) )
1675 {
1676 // probe it
1677 dll->probe();
1678 // if not compatible
1679 if( !dll->compatible() )
1680 {
1681 // print `[chugin] X.chug`
1682 logChuginLoad( name, CK_LOG_HERALD );
1683 // print
1684 EM_log_opts( CK_LOG_HERALD, EM_LOG_NO_PREFIX, "[%s] (API version: %d.%d)", TC::red("FAILED",true).c_str(), dll->versionMajor(), dll->versionMinor() );
1685 // push
1686 EM_pushlog();
1687 EM_log( CK_LOG_HERALD, "reason: %s", TC::orange(dll->last_error(),true).c_str() );
1688 EM_poplog();
1689 // set error string
1690 errorStr = dll->last_error();
1691 // go to error for cleanup
1692 goto error;
1693 }
1694
1695 // try to query the chugin
1696 query_failed = !dll->query();
1697 // try to add to type system
1698 if( query_failed || !type_engine_add_dll2( env, dll, "global" ) )
1699 {
1700 // print `[chugin] X.chug`
1701 logChuginLoad( name, CK_LOG_HERALD );
1702 // print
1703 EM_log_opts( CK_LOG_HERALD, EM_LOG_NO_PREFIX, "[%s] (API version: %d.%d)", TC::red("FAILED",true).c_str(), dll->versionMajor(), dll->versionMinor() );
1704 EM_pushlog();
1705 // if add_dll2 failed, an error should have already been output
1706 if( query_failed )
1707 {
1708 // print reason
1709 EM_log( CK_LOG_HERALD, "reason: %s", TC::orange(dll->last_error(),true).c_str() );
1710 }
1711 EM_log( CK_LOG_HERALD, "%s '%s'...", TC::blue("skipping",true).c_str(), path.c_str() );
1712 EM_poplog();
1713 // set error string
1714 errorStr = dll->last_error();
1715 // go to error for cleanup
1716 goto error;
1717 }
1718 }
1719 else
1720 {
1721 // print `[chugin] X.chug`
1722 logChuginLoad( name, CK_LOG_HERALD );
1723 // print error status
1724 EM_log_opts( CK_LOG_HERALD, EM_LOG_NO_PREFIX, "[%s]", TC::red("FAILED",true).c_str() );
1725 // more info
1726 EM_pushlog();
1727 EM_log( CK_LOG_HERALD, "reason: %s", TC::orange(dll->last_error(),true).c_str() );
1728 EM_poplog();
1729 // set error string
1730 errorStr = dll->last_error();
1731 // go to error for cleanup
1732 goto error;
1733 }
1734
1735 // print `[chugin] X.chug`
1736 logChuginLoad( name, CK_LOG_HERALD );
1737 // print success status
1738 EM_log_opts( CK_LOG_HERALD, EM_LOG_NO_PREFIX, "[%s]", TC::green("OK",true).c_str() );
1739 // add to registry
1740 m_importRegistry.commit( dll );
1741 // commit operator overloads | 1.5.1.5
1742 env->op_registry.preserve();
1743
1744 // return home successful
1745 return TRUE;
1746
1747 error:
1748 // clean up
1749 CK_SAFE_DELETE( dll );
1750 // rollback operator overloads | 1.5.1.5
1751 env->op_registry.reset2local();
1752
1753 // return home :(
1754 return FALSE;
1755 }
1756
1757
1758
1759
1760 //-----------------------------------------------------------------------------
1761 // name: load_external_modules_in_directory()
1762 // desc: load all external modules by extension within a directory
1763 //-----------------------------------------------------------------------------
1764 t_CKBOOL Chuck_Compiler::load_external_modules_in_directory(
1765 const string & directory,
1766 const string & extension,
1767 t_CKBOOL recursiveSearch )
1768 {
1769 vector<ChuginFileInfo> chugins2load;
1770 vector<string> dirs2search;
1771 vector<string> ckfiles2load;
1772 string errorStr;
1773
1774 // print directory to examine
1775 EM_log( CK_LOG_HERALD, "searching '%s'", format_dir_name_for_display(directory).c_str() );
1776 // push
1777 EM_pushlog();
1778
1779 // scan
1780 t_CKBOOL retval = scan_external_modules_in_directory( directory, extension, recursiveSearch, chugins2load, dirs2search, ckfiles2load );
1781 if( !retval )
1782 {
1783 // log (1.3.1.2: changed to 2 lines to stay within 80 chars)
1784 EM_log( CK_LOG_INFO, "unable to open directory..." );
1785 EM_log( CK_LOG_INFO, "ignoring for chugins..." );
1786 // pop
1787 EM_poplog();
1788 // go ahead and return true
1789 return TRUE;
1790 }
1791
1792 // sort
1793 sort( chugins2load.begin(), chugins2load.end(), comp_func_chuginfileinfo );
1794 sort( dirs2search.begin(), dirs2search.end() );
1795 sort( ckfiles2load.begin(), ckfiles2load.end() );
1796
1797 // loop over chugins to load
1798 for( t_CKINT i = 0; i < chugins2load.size(); i++ )
1799 {
1800 // load module
1801 // ...in its own namespace == FALSE | 1.5.4.0 (ge) added
1802 // ...since already in namespace (e.g., @[external]) from load_external_modules()
1803 t_CKBOOL loaded = this->importChugin( chugins2load[i].path, FALSE, chugins2load[i].filename, errorStr );
1804 // if no error
1805 if( chugins2load[i].isBundle && loaded) {
1806 // log
1807 EM_pushlog();
1808 EM_log( CK_LOG_INFO, "macOS bundle was detected..." );
1809 string shortenSubdir = chugins2load[i].path;
1810 shortenSubdir = shortenSubdir.substr( shortenSubdir.find( chugins2load[i].filename ) );
1811 EM_log( CK_LOG_INFO, "loaded %s", shortenSubdir.c_str() );
1812 EM_poplog();
1813 }
1814 }
1815
1816 // loop over ck files to load (later)
1817 for( t_CKINT i = 0; i < ckfiles2load.size(); i++ )
1818 {
1819 // save for later
1820 this->m_cklibs_to_preload.push_back( ckfiles2load[i] );
1821 }
1822
1823 // pop log
1824 EM_poplog();
1825
1826 // loop over dirs2 to search | if not recursive, this should be empty
1827 for( t_CKINT i = 0; i < dirs2search.size(); i++ )
1828 {
1829 // search in dir
1830 load_external_modules_in_directory( dirs2search[i], extension, recursiveSearch );
1831 }
1832
1833 return TRUE;
1834 }
1835
1836
1837
1838
1839 //-----------------------------------------------------------------------------
1840 // name: load_external_modules()
1841 // desc: load external modules (e.g., .chug and .ck library files)
1842 //-----------------------------------------------------------------------------
1843 t_CKBOOL Chuck_Compiler::load_external_modules( const string & extension,
1844 list<string> & chugin_search_paths,
1845 list<string> & named_dls,
1846 t_CKBOOL recursiveSearch )
1847 {
1848 // get env
1849 Chuck_Env * env = this->env();
1850 // make context
1851 Chuck_Context * context = type_engine_make_context( NULL, "@[external]" );
1852 // reset env - not needed since we just created the env
1853 env->reset();
1854 // load it
1855 type_engine_load_context( env, context );
1856
1857 // first load dynamic libraries explicitly named on the command line
1858 for( list<string>::iterator i_dl = named_dls.begin();
1859 i_dl != named_dls.end(); i_dl++ )
1860 {
1861 // get chugin name
1862 std::string & dl_path = *i_dl;
1863 // error string
1864 std::string error_str;
1865 // expand the filepath (e.g., ~) | 1.5.2.6 (ge) added
1866 dl_path = expand_filepath( dl_path );
1867 // get full path | 1.5.4.2 (ge) added
1868 dl_path = normalize_filepath_append_ck( dl_path ); // append ck necessary?
1869 // check extension, append if no match
1870 if( !extension_matches( dl_path, extension ) )
1871 dl_path += extension;
1872 // load the module, in its own namespace == FALSE
1873 this->importChugin( dl_path, FALSE, mini(dl_path.c_str()), error_str );
1874 }
1875
1876 // now recurse through search paths and load any .chug files found
1877 for( list<string>::iterator i_sp = chugin_search_paths.begin();
1878 i_sp != chugin_search_paths.end(); i_sp++ )
1879 {
1880 // expand the filepath (e.g., ~) | 1.5.2.6 (ge) added
1881 string dl_path = expand_filepath( *i_sp );
1882 // get full path | 1.5.4.2 (ge) added
1883 dl_path = normalize_filepath( dl_path, TRUE );
1884 // search directory and load contents
1885 load_external_modules_in_directory( dl_path, extension, recursiveSearch );
1886 }
1887
1888 // clear context
1889 type_engine_unload_context( env );
1890 // commit what is in the type checker at this point
1891 env->global()->commit();
1892 // preserve all operator overloads currently in registry | 1.5.1.5
1893 env->op_registry.preserve();
1894
1895 // always return true...
1896 // a failed chugin load should not prevent chuck from starting
1897 return TRUE;
1898 }
1899
1900
1901
1902
1903 //-----------------------------------------------------------------------------
1904 // name: probe_external_chugin()
1905 // desc: probe external module by path
1906 //-----------------------------------------------------------------------------
1907 t_CKBOOL Chuck_Compiler::probe_external_chugin( const string & path, const string & theName )
1908 {
1909 // name
1910 string name = theName != "" ? theName : extract_filepath_file(path);
1911 // create dynamic module
1912 Chuck_DLL * dll = new Chuck_DLL( NULL, name.c_str() );
1913
1914 // NOTE this (verbose >= 5) is more informative if the chugin crashes, we can see the name
1915 EM_log( CK_LOG_INFO, "probing [chugin] %s...", name.c_str() );
1916 EM_log( CK_LOG_FINE, " |- path: '%s'", path.c_str() );
1917
1918 // load the dll, lazy mode
1919 if( dll->load(path.c_str(), CK_QUERY_FUNC, TRUE) )
1920 {
1921 // probe it
1922 dll->probe();
1923 // if not compatible
1924 if( dll->compatible() )
1925 {
1926 // print `[chugin] X.chug`
1927 logChuginLoad( name, CK_LOG_SYSTEM );
1928 // print
1929 EM_log_opts( CK_LOG_SYSTEM, EM_LOG_NO_PREFIX, "[%s] (API version: %d.%d)", TC::green("OK",true).c_str(),
1930 dll->versionMajor(), dll->versionMinor() );
1931 }
1932 else
1933 {
1934 // print `[chugin] X.chug`
1935 logChuginLoad( name, CK_LOG_SYSTEM );
1936 // print
1937 EM_log_opts( CK_LOG_SYSTEM, EM_LOG_NO_PREFIX, "[%s] (API version: %d.%d)", TC::red("FAILED",true).c_str(),
1938 dll->versionMajor(), dll->versionMinor() );
1939 // push
1940 EM_pushlog();
1941 EM_log( CK_LOG_SYSTEM, "reason: %s", TC::orange(dll->last_error(),true).c_str() );
1942 EM_poplog();
1943 }
1944
1945 // print info if available
1946 string dllName = dll->name();
1947 string dllPath = dll->filepath();
1948 string authors = dll->getinfo( CHUGIN_INFO_AUTHORS );
1949 string version = dll->getinfo( CHUGIN_INFO_CHUGIN_VERSION );
1950 string desc = dll->getinfo( CHUGIN_INFO_DESCRIPTION );
1951 string url = dll->getinfo( CHUGIN_INFO_URL );
1952 string email = dll->getinfo( CHUGIN_INFO_EMAIL );
1953
1954 // print additional information
1955 if( authors.length() || version.length() || desc.length() || url.length() )
1956 {
1957 EM_pushlog();
1958 if( version.length() ) EM_log( CK_LOG_SYSTEM, "version: %s", version.c_str() );
1959 if( authors.length() ) EM_log( CK_LOG_SYSTEM, "author: %s", authors.c_str() );
1960 if( desc.length() ) EM_log( CK_LOG_HERALD, "description: %s", desc.c_str() );
1961 if( url.length() ) EM_log( CK_LOG_HERALD, "URL: %s", url.c_str() );
1962 if( email.length() ) EM_log( CK_LOG_INFO, "email: %s", email.c_str() );
1963 EM_poplog();
1964 }
1965 }
1966 else
1967 {
1968 // print `[chugin] X.chug`
1969 logChuginLoad( name, CK_LOG_SYSTEM );
1970 // print
1971 EM_log_opts( CK_LOG_SYSTEM, EM_LOG_NO_PREFIX, "[%s]...", TC::red("FAILED",true).c_str() );
1972 // more info
1973 EM_pushlog();
1974 EM_log( CK_LOG_SYSTEM, "reason: %s", TC::orange(dll->last_error(),true).c_str() );
1975 EM_poplog();
1976 }
1977
1978 // clean up | 1.5.4.1 (ge) added
1979 CK_SAFE_DELETE( dll );
1980
1981 // done
1982 return TRUE;
1983 }
1984
1985
1986
1987
1988 //-----------------------------------------------------------------------------
1989 // name: probe_external_modules_in_directory()
1990 // desc: probe all external modules by extension within a directory
1991 //-----------------------------------------------------------------------------
1992 t_CKBOOL Chuck_Compiler::probe_external_modules_in_directory(
1993 const string & directory,
1994 const string & extension,
1995 t_CKBOOL recursiveSearch,
1996 list<string> & ck_libs )
1997 {
1998 vector<ChuginFileInfo> chugins2load;
1999 vector<string> dirs2search;
2000 vector<string> ckfiles2load;
2001
2002 // print directory to examine
2003 EM_log( CK_LOG_SYSTEM, "searching '%s'", format_dir_name_for_display(directory).c_str() );
2004 // push
2005 EM_pushlog();
2006
2007 // scan
2008 t_CKBOOL retval = scan_external_modules_in_directory( directory, extension, recursiveSearch, chugins2load, dirs2search, ckfiles2load );
2009 if( !retval )
2010 {
2011 // log (1.3.1.2: changed to 2 lines to stay within 80 chars)
2012 EM_log( CK_LOG_INFO, "unable to open directory..." );
2013 EM_log( CK_LOG_INFO, "ignoring for chugins..." );
2014 // pop log
2015 EM_poplog();
2016 // go ahead and return true
2017 return TRUE;
2018 }
2019
2020 // sort
2021 sort( chugins2load.begin(), chugins2load.end(), comp_func_chuginfileinfo );
2022 sort( dirs2search.begin(), dirs2search.end() );
2023 sort( ckfiles2load.begin(), ckfiles2load.end() );
2024
2025 // loop over chugins to load
2026 for( t_CKINT i = 0; i < chugins2load.size(); i++ )
2027 {
2028 // load module
2029 t_CKBOOL probed = probe_external_chugin(
2030 chugins2load[i].path, chugins2load[i].filename );
2031 // if no error
2032 if( chugins2load[i].isBundle && probed) {
2033 // log
2034 EM_pushlog();
2035 EM_log( CK_LOG_INFO, "macOS bundle was detected..." );
2036 string shortenSubdir = chugins2load[i].path;
2037 shortenSubdir = shortenSubdir.substr( shortenSubdir.find( chugins2load[i].filename ) );
2038 EM_log( CK_LOG_INFO, "loaded %s", shortenSubdir.c_str() );
2039 EM_poplog();
2040 }
2041 }
2042
2043 // loop over ck files to load (later)
2044 for( t_CKINT i = 0; i < ckfiles2load.size(); i++ )
2045 {
2046 // save for later
2047 ck_libs.push_back( ckfiles2load[i] );
2048 }
2049
2050 // pop log
2051 EM_poplog();
2052
2053 // loop over dirs2 to search | if not recursive, this should be empty
2054 for( t_CKINT i = 0; i < dirs2search.size(); i++ )
2055 {
2056 // search in dir
2057 probe_external_modules_in_directory( dirs2search[i], extension, recursiveSearch, ck_libs );
2058 }
2059
2060 return TRUE;
2061 }
2062
2063
2064
2065
2066 //-----------------------------------------------------------------------------
2067 // name: probe_external_modules()
2068 // desc: probe external modules (e.g., .chug and .ck library files)
2069 //-----------------------------------------------------------------------------
2070 t_CKBOOL Chuck_Compiler::probe_external_modules( const string & extension,
2071 list<string> & chugin_search_paths,
2072 list<string> & named_dls,
2073 t_CKBOOL recursiveSearch,
2074 list<string> & ck_libs )
2075 {
2076 // print
2077 EM_log( CK_LOG_SYSTEM, "probing specified chugins (e.g., via --chugin)..." );
2078 // push
2079 EM_pushlog();
2080
2081 // first load dynamic libraries explicitly named on the command line
2082 for( list<string>::iterator i_dl = named_dls.begin();
2083 i_dl != named_dls.end(); i_dl++ )
2084 {
2085 // get chugin name
2086 std::string & dl_path = *i_dl;
2087 // expand the filepath (e.g., ~) | 1.5.2.6 (ge) added
2088 dl_path = expand_filepath( dl_path );
2089 // get full path | 1.5.4.2 (ge) added
2090 dl_path = normalize_filepath_append_ck( dl_path ); // append ck necessary?
2091 // check extension, append if no match
2092 if( !extension_matches( dl_path, extension ) )
2093 dl_path += extension;
2094 // load the module
2095 probe_external_chugin( dl_path, mini(dl_path.c_str()) );
2096 }
2097
2098 // check
2099 if( named_dls.size() == 0 )
2100 EM_log( CK_LOG_INFO, "(none specified)" );
2101
2102 // pop
2103 EM_poplog();
2104 // print
2105 EM_log( CK_LOG_SYSTEM, "probing chugins in search paths..." );
2106 // push
2107 EM_pushlog();
2108
2109 // now recurse through search paths and note any .chug files found
2110 for( list<string>::iterator i_sp = chugin_search_paths.begin();
2111 i_sp != chugin_search_paths.end(); i_sp++ )
2112 {
2113 // expand the filepath (e.g., ~) | 1.5.2.6 (ge) added
2114 string dl_path = expand_filepath( *i_sp );
2115 // get full path | 1.5.4.2 (ge) added
2116 dl_path = normalize_filepath( dl_path, TRUE );
2117 // search directory and load contents
2118 probe_external_modules_in_directory( dl_path, extension, recursiveSearch, ck_libs );
2119 }
2120
2121 // pop
2122 EM_poplog();
2123
2124 return TRUE;
2125 }
2126
2127
2128
2129
2130 //-----------------------------------------------------------------------------
2131 // name: setAutoDepend()
2132 // desc: auto dependency resolve for types
2133 //-----------------------------------------------------------------------------
2134 void Chuck_Compiler::setAutoDepend( t_CKBOOL v )
2135 {
2136 // log
2137 EM_log( CK_LOG_SYSTEM, "type dependency resolution: %s",
2138 v ? "AUTO" : "MANUAL" );
2139 m_auto_depend = v;
2140 }
2141
2142
2143
2144
2145 //-----------------------------------------------------------------------------
2146 // name: resolve()
2147 // desc: resolve type automatically - if auto_depend is off, return FALSE
2148 //-----------------------------------------------------------------------------
2149 t_CKBOOL Chuck_Compiler::resolve( const string & type )
2150 {
2151 t_CKBOOL ret = TRUE;
2152
2153 // check auto_depend
2154 if( !m_auto_depend )
2155 return FALSE;
2156
2157 // look up if name is already parsed
2158
2159 return ret;
2160 }
2161
2162
2163
2164
2165 //-----------------------------------------------------------------------------
2166 // name: Chuck_ImportRegistry()
2167 // desc: constructor
2168 //-----------------------------------------------------------------------------
2169 Chuck_ImportRegistry::Chuck_ImportRegistry()
2170 { }
2171
2172
2173
2174
2175 //-----------------------------------------------------------------------------
2176 // name: lookupTarget()
2177 // desc: look up if target exists by path (relative or full)
2178 //-----------------------------------------------------------------------------
2179 Chuck_CompileTarget * Chuck_ImportRegistry::lookup( const std::string & path,
2180 Chuck_CompileTarget * importer )
2181 {
2182 // ignore if not importing
2183 if( !importer ) return NULL;
2184
2185 // return value
2186 Chuck_CompileTarget * ret = NULL;
2187 // search path
2188 std::string key = expand_filepath( path );
2189
2190 // log
2191 EM_log( CK_LOG_FINER, "@import registry search: '%s' ", path.c_str() );
2192
2193 // if importer is a file
2194 if( importer->filename != CHUCK_CODE_LITERAL_SIGNIFIER )
2195 {
2196 // transplant to absolute path, resolves to realpath
2197 key = transplant_filepath( importer->absolutePath, key );
2198 }
2199 else // if not, importer is code
2200 {
2201 // if not an absolute path
2202 if( !is_absolute_path( key ) )
2203 {
2204 // use the current working directory
2205 key = importer->the_chuck->getParamString( CHUCK_PARAM_WORKING_DIRECTORY ) + path;
2206 }
2207 }
2208
2209 // push log
2210 EM_pushlog();
2211
2212 // attempt to find in done list
2213 map<string, Chuck_CompileTarget *>::iterator it = m_importedTargets.find( key );
2214 // if not found
2215 if( it != m_importedTargets.end() )
2216 {
2217 ret = it->second;
2218 // log (if import only)
2219 EM_log( CK_LOG_FINER, "found (compiled): '%s'", key.c_str() );
2220 }
2221
2222 // if not found
2223 if( !ret )
2224 {
2225 // attempt to find in in-progress list
2226 it = m_inProgressCKFiles.find( key );
2227 // if not found
2228 if( it != m_inProgressCKFiles.end() )
2229 {
2230 ret = it->second;
2231 // log
2232 EM_log( CK_LOG_FINER, "found (in-progress): '%s'", key.c_str() );
2233 }
2234 }
2235
2236 // if still not found
2237 if( !ret )
2238 { EM_log( CK_LOG_FINER, "(not found)" ); }
2239
2240 // pop log (if import only)
2241 EM_poplog();
2242
2243 // return findings
2244 return ret;
2245 }
2246
2247
2248
2249
2250 //-----------------------------------------------------------------------------
2251 // name: addTarget()
2252 // desc: add a new compile target to import system
2253 //-----------------------------------------------------------------------------
2254 t_CKBOOL Chuck_ImportRegistry::addInProgress( Chuck_CompileTarget * target )
2255 {
2256 // check
2257 if( !target ) return FALSE;
2258
2259 // cannot add if key already exists
2260 if( m_inProgressCKFiles.find( target->key() ) != m_inProgressCKFiles.end() )
2261 {
2262 // internal error; should have been verified before calling this function
2263 EM_error2( 0, "(import registry) cannot add target to in-progress list..." );
2264 EM_error2( 0, " |- '%s' already present...", target->key().c_str() );
2265 return FALSE;
2266 }
2267
2268 // insert
2269 m_inProgressCKFiles[target->key()] = target;
2270 // return
2271 return TRUE;
2272 }
2273
2274
2275
2276
2277 //-----------------------------------------------------------------------------
2278 // name: commit()
2279 // desc: move target from in progress to imported list
2280 //-----------------------------------------------------------------------------
2281 void Chuck_ImportRegistry::commit( Chuck_CompileTarget * target )
2282 {
2283 // check
2284 if( !target ) return;
2285
2286 // set state to COMPLETE
2287 target->state = te_compile_complete;
2288 // get key
2289 string key = target->key();
2290
2291 // remove from in-progress list
2292 m_inProgressCKFiles.erase( key );
2293
2294 // check if in map
2295 if( m_importedTargets.find( key ) != m_importedTargets.end() )
2296 {
2297 // warn
2298 EM_log( CK_LOG_WARNING, "import registry duplicate imported target: '%s'", key.c_str() );
2299 }
2300
2301 // should be safe to cleanup AST and close any file handles
2302 target->cleanup();
2303
2304 // insert into imported map
2305 m_importedTargets[key] = target;
2306 }
2307
2308
2309
2310
2311 //-----------------------------------------------------------------------------
2312 // name: commit()
2313 // desc: add a chugin to the imported list
2314 //-----------------------------------------------------------------------------
2315 Chuck_CompileTarget * Chuck_ImportRegistry::commit( Chuck_DLL * chugin )
2316 {
2317 // check
2318 if( !chugin ) return NULL;
2319
2320 // get key
2321 string key = chugin->filepath();
2322
2323 // check if key in map
2324 if( m_importedTargets.find( key ) != m_importedTargets.end() )
2325 {
2326 // already there; return corresponding target
2327 return m_importedTargets.find( key )->second;
2328 }
2329
2330 // insert into chugin map
2331 m_importedChugins[key] = chugin;
2332
2333 // make new target for chugin
2334 Chuck_CompileTarget * t = new Chuck_CompileTarget( te_do_all );
2335 // set appropriate settings for chugin
2336 t->chugin = chugin;
2337 // is complete
2338 t->state = te_compile_complete;
2339 // all chugins are considered "system" (and will persists across VM clears)
2340 t->isSystemImport = TRUE;
2341 // set name to chugin short hand
2342 t->filename = extract_filepath_file(key);
2343 // set absolute path
2344 t->absolutePath = key;
2345
2346 // insert into import map
2347 m_importedTargets[key] = t;
2348
2349 // return the target
2350 return t;
2351 }
2352
2353
2354
2355
2356 //-----------------------------------------------------------------------------
2357 // name: clearInProgress()
2358 // desc: remove in-progress targets
2359 //-----------------------------------------------------------------------------
2360 void Chuck_ImportRegistry::clearInProgress()
2361 {
2362 // iterator
2363 map<string, Chuck_CompileTarget *>::iterator it;
2364 // iterate
2365 for( it = m_inProgressCKFiles.begin(); it != m_inProgressCKFiles.end(); it++ )
2366 {
2367 // delete the target
2368 CK_SAFE_DELETE( it->second );
2369 }
2370 // clear map
2371 m_inProgressCKFiles.clear();
2372 }
2373
2374
2375
2376
2377 //-----------------------------------------------------------------------------
2378 // name: clearAllUserImports()
2379 // desc: remove all user imports (system imports unaffected)
2380 //-----------------------------------------------------------------------------
2381 void Chuck_ImportRegistry::clearAllUserImports()
2382 {
2383 // clear in progress
2384 clearInProgress();
2385
2386 // list of iterators to erase after iterating
2387 vector<string> itersToErase;
2388
2389 // clear imported CK Files
2390 map<std::string, Chuck_CompileTarget *>::iterator iterT;
2391 for( iterT = m_importedTargets.begin(); iterT != m_importedTargets.end(); iterT++ )
2392 {
2393 if( iterT->second->isSystemImport == FALSE )
2394 {
2395 // delete each imported CK file
2396 CK_SAFE_DELETE( iterT->second );
2397 // add key to list to be erased after this loop
2398 itersToErase.push_back( iterT->first );
2399 }
2400 }
2401
2402 // erase entries from map
2403 for( t_CKINT i = 0; i < itersToErase.size(); i++ )
2404 {
2405 // erase each entry by key
2406 m_importedTargets.erase( itersToErase[i] );
2407 }
2408 }
2409
2410
2411
2412
2413 //-----------------------------------------------------------------------------
2414 // name: isChuginLoaded()
2415 // desc: check if a same-name chugin is already imported, ignoring path
2416 //-----------------------------------------------------------------------------
2417 t_CKBOOL Chuck_ImportRegistry::isChuginLoaded( const std::string & path )
2418 {
2419 // remove path before chugin name and lower case
2420 std::string name = tolower( extract_filepath_file( path ) );
2421
2422 // iterate
2423 map<std::string, Chuck_DLL *>::iterator iterC;
2424 for( iterC = m_importedChugins.begin(); iterC != m_importedChugins.end(); iterC++ )
2425 {
2426 // get the chugin
2427 Chuck_DLL * chugin = iterC->second;
2428 // remove path portion and lower case
2429 std::string chugin_name = tolower( extract_filepath_file( chugin->filepath() ) );
2430 // compare name
2431 if( name == chugin_name ) return TRUE;
2432 }
2433
2434 // no match found
2435 return FALSE;
2436 }
2437
2438
2439
2440
2441 //-----------------------------------------------------------------------------
2442 // name: shutdown()
2443 // desc: remove all imports (system and user)
2444 //-----------------------------------------------------------------------------
2445 void Chuck_ImportRegistry::shutdown()
2446 {
2447 // clear in progress
2448 clearInProgress();
2449
2450 // clear imported CK Files
2451 map<std::string, Chuck_CompileTarget *>::iterator iterT;
2452 for( iterT = m_importedTargets.begin(); iterT != m_importedTargets.end(); iterT++ )
2453 {
2454 // delete each DLL
2455 CK_SAFE_DELETE( iterT->second );
2456 }
2457 // clear the map
2458 m_importedTargets.clear();
2459
2460 // clean up imported chugins
2461 map<std::string, Chuck_DLL *>::iterator iterC;
2462 for( iterC = m_importedChugins.begin(); iterC != m_importedChugins.end(); iterC++ )
2463 {
2464 // delete each DLL
2465 CK_SAFE_DELETE( iterC->second );
2466 }
2467 // clear the list
2468 m_importedChugins.clear();
2469 }
2470
2471
2472
2473
2474 //-----------------------------------------------------------------------------
2475 // name: cleanupAST()
2476 // desc: clean up abstract syntax tree in target
2477 //-----------------------------------------------------------------------------
2478 void Chuck_CompileTarget::cleanupAST()
2479 {
2480 // clean up abstract syntax tree
2481 if( AST )
2482 {
2483 // delete tree
2484 delete_program( AST );
2485 // null out
2486 AST = NULL;
2487 }
2488 }
2489
2490
2491
2492
2493 //-----------------------------------------------------------------------------
2494 // name: cleanup()
2495 // desc: performs cleanup (e.g., close file descriptors and reclaims AST)
2496 // prepares target to be archived in import system after successful compilation
2497 //-----------------------------------------------------------------------------
2498 void Chuck_CompileTarget::cleanup()
2499 {
2500 // clean up abstract syntax tree
2501 cleanupAST();
2502
2503 // clean up the file source
2504 fileSource.reset();
2505
2506 // if open
2507 if( fd2parse )
2508 {
2509 // close file descriptor
2510 fclose( fd2parse );
2511 // null out
2512 fd2parse = NULL;
2513 }
2514
2515 // free the intList
2516 IntList curr = NULL;
2517 while( the_linePos )
2518 {
2519 curr = the_linePos;
2520 the_linePos = the_linePos->rest;
2521 // free
2522 free( curr );
2523 }
2524 // make new intList
2525 the_linePos = intList( 0, NULL );
2526
2527 // reset line number
2528 lineNum = 1;
2529 }
2530
2531
2532
2533
2534 //-----------------------------------------------------------------------------
2535 // name: openFile()
2536 // desc: open a file
2537 // * resolve and set filename and absolutePath for a compile target
2538 // * set as filename (possibly with modifications, e.g., with .ck appended)
2539 // * if file is unresolved locally and `expandSearchToGlobal` is true,
2540 // expand search to global search paths
2541 // * the file is resolved this will open a FILE descriptor in fd2parse
2542 //-----------------------------------------------------------------------------
2543 t_CKBOOL Chuck_Compiler::openFile( Chuck_CompileTarget * target,
2544 const std::string & theFilename,
2545 Chuck_CompileTarget * importer,
2546 t_CKBOOL expandSearchToGlobal,
2547 t_CKINT wherePos )
2548 {
2549 // clean up
2550 target->cleanup();
2551
2552 // reset fields (in case of error)
2553 target->filename = "";
2554 target->absolutePath = "";
2555 target->codeLiteral = "";
2556
2557 // resolve
2558 target->absolutePath = resolveFilename( theFilename, importer ? importer->absolutePath : "", expandSearchToGlobal );
2559 // if unresolved
2560 if( target->absolutePath == "" )
2561 {
2562 // print error
2563 EM_error2( wherePos, "no such file: '%s'", mini( theFilename.c_str() ) );
2564 // done
2565 return FALSE;
2566 }
2567
2568 // check for directory
2569 if( ck_isdir( target->absolutePath ) )
2570 {
2571 // print error
2572 EM_error2( wherePos, "cannot parse file: '%s' is a directory", mini(target->absolutePath.c_str()) );
2573 // done
2574 return FALSE;
2575 }
2576
2577 // open file
2578 target->fd2parse = fopen( target->absolutePath.c_str(), "rb" );
2579 // if still unresolved
2580 if( !target->fd2parse )
2581 {
2582 // print error
2583 EM_error2( wherePos, "cannot open file: '%s'", target->absolutePath.c_str() );
2584 // done
2585 return FALSE;
2586 }
2587
2588 // set file descriptor to beginning
2589 fseek( target->fd2parse, 0, SEEK_SET );
2590
2591 // shorthand name
2592 target->filename = mini(target->absolutePath.c_str());
2593
2594 // done
2595 return TRUE;
2596 }