Analyze PHPConsistent data from trace file
336699
public function analyze()
    {
        if (!file_exists($this->_traceFile)) {
            return false;
        }
        $this->processFunctionCalls();
        unlink($this->_traceFile);
        if (file_exists($this->_traceFile . '.xt')) {
            unlink($this->_traceFile . '.xt');
        }

        if (count($this->_failures) > 0) {
            return $this->_failures;
        } else {
		    return array();
		}
    }
294855
private function traceHTML(array $trace) {
            ?>
            <table class="table" border="1">
                <thead>
                <tr>
                    <th>#</th>
                    <th>Method</th>
                    <th>Args</th>
                    <th>File</th>
                    <th>Line</th>
                </tr>
                </thead>
                <tbody><?php
                    foreach ($trace as $k => $v) {
                        $func = $loc = $line = '';
                        self::formatTraceLine($v, $func, $loc, $line);

                        if (isset($v['args']) && !empty($v['args'])) {
                            $args = Dump::html($v['args']);
                        } else {
                            $args = '<span class="label label-default">[none]</span>';
                        }

                        ?>
                        <tr>
                            <td><?= $k ?></td>
                            <td><?= $func ?></td>
                            <td class="text-center"><?= $args ?></td>
                            <td><?= $loc ? $loc : '<span class="label label-default">???</label>' ?></td>
                            <td><?= ($line == 0 || trim($line)) ? $line :
                                    '<span class="label label-default">???</span>' ?></td>
                        </tr>

                        <?php
                    }
                ?>
                </tbody>
            </table>
            <?php
        }
761427
public static function inspect()
	{
		$backtrace = debug_backtrace();

		// If being called from within, show the file above in the backtrack
		if (strpos($backtrace[0]['file'], 'core/classes/debug.php') !== false)
		{
			$callee = $backtrace[1];
			$label = \Inflector::humanize($backtrace[1]['function']);
		}
		else
		{
			$callee = $backtrace[0];
			$label = 'Debug';
		}

		$arguments = func_get_args();
		$total_arguments = count($arguments);

		$callee['file'] = \Fuel::clean_path($callee['file']);

		if ( ! static::$js_displayed)
		{
			echo <<<JS
<script type="text/javascript">function fuel_debug_toggle(a){if(document.getElementById){if(document.getElementById(a).style.display=="none"){document.getElementById(a).style.display="block"}else{document.getElementById(a).style.display="none"}}else{if(document.layers){if(document.id.display=="none"){document.id.display="block"}else{document.id.display="none"}}else{if(document.all.id.style.display=="none"){document.all.id.style.display="block"}else{document.all.id.style.display="none"}}}};</script>
JS;
			static::$js_displayed = true;
		}
		echo '<div class="fuelphp-inspect" style="font-size: 13px;background: #EEE !important; border:1px solid #666; color: #000 !important; padding:10px;">';
		echo '<h1 style="border-bottom: 1px solid #CCC; padding: 0 0 5px 0; margin: 0 0 5px 0; font: bold 120% sans-serif;">'.$callee['file'].' @ line: '.$callee['line'].'</h1>';
		echo '<pre style="overflow:auto;font-size:100%;">';
		$i = 0;
		foreach ($arguments as $argument)
		{
			echo '<strong>'.$label.' #'.(++$i).' of '.$total_arguments.'</strong>:<br />';
				echo static::format('...', $argument);
			echo '<br />';
		}

		echo "</pre>";
		echo "</div>";
	}
973889
def exception_info(current_filename=None, index=-1):
    ""
    # guardo el traceback original (por si hay una excepción):
    info = sys.exc_info() #         exc_type, exc_value, exc_traceback
    # importante: no usar unpacking porque puede causar memory leak
    if not current_filename:
        # genero un call stack para ver quien me llamó y limitar la traza: 
        # advertencia: esto es necesario ya que en py2exe no tengo __file__ 
        try:
            raise ZeroDivisionError
        except ZeroDivisionError:
            f = sys.exc_info()[2].tb_frame.f_back
        current_filename = os.path.normpath(os.path.abspath(f.f_code.co_filename))

    # extraer la última traza del archivo solicitado:
    # (útil para no alargar demasiado la traza con lineas de las librerías)
    ret = {'filename': "", 'lineno': 0, 'function_name': "", 'code': ""}
    try:
        for (filename, lineno, fn, text) in traceback.extract_tb(info[2]):
            if os.path.normpath(os.path.abspath(filename)) == current_filename:
                ret = {'filename': filename, 'lineno': lineno, 
                       'function_name': fn, 'code': text}
    except Exception, e:
        pass
    # obtengo el mensaje de excepcion tal cual lo formatea python:
    # (para evitar errores de encoding)
    try:
        ret['msg'] = traceback.format_exception_only(*info[0:2])[0]
    except: 
        ret['msg'] = '<no disponible>'
    # obtener el nombre de la excepcion (ej. "NameError")
    try:
        ret['name'] = info[0].__name__
    except:
        ret['name'] = 'Exception'
    # obtener la traza formateada como string:
    try:
        tb = traceback.format_exception(*info)
        ret['tb'] = ''.join(tb)
    except:
        ret['tb'] = ""
    return ret
1360065
public static function trace()
    {
        if (!self::$enabled_mode) {
            return 0;
        }

        Utils::normalizeAliases(self::$aliases);

        $args = \func_get_args();

        $call_info = self::getCallInfo(self::$aliases, \debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), \count($args));

        $statics = self::getStatics();

        if (\in_array('~', $call_info['modifiers'], true)) {
            $statics['enabled_mode'] = self::MODE_TEXT;
        }

        $kintstance = self::createFromStatics($statics);
        if (!$kintstance) {
            // Should never happen
            return 0; // @codeCoverageIgnore
        }

        if (\in_array('-', $call_info['modifiers'], true)) {
            while (\ob_get_level()) {
                \ob_end_clean();
            }
        }

        $kintstance->setStatesFromStatics($statics);
        $kintstance->setStatesFromCallInfo($call_info);

        $trimmed_trace = array();
        $trace = \debug_backtrace(true);

        foreach ($trace as $frame) {
            if (Utils::traceFrameIsListed($frame, self::$aliases)) {
                $trimmed_trace = array();
            }

            $trimmed_trace[] = $frame;
        }

        $output = $kintstance->dumpAll(
            array($trimmed_trace),
            array(BasicObject::blank('Kint\\Kint::trace()', 'debug_backtrace(true)'))
        );

        if (self::$return || \in_array('@', $call_info['modifiers'], true)) {
            return $output;
        }

        echo $output;

        if (\in_array('-', $call_info['modifiers'], true)) {
            \flush(); // @codeCoverageIgnore
        }

        return 0;
    }
1084121
function formatDebugTrace(array $backtrace)
    {
        $rV = '';

        foreach ($backtrace as $trace) {
            $functionName = $traceStr = $trace['function'];
            $args = \join(', ', $trace['args']);
            $className = empty($trace['class'])
                ? ''
                : $traceStr = $trace['class'] . '::';
            $parameters = \count($trace['args']) > 0
                ? '( ' . $args . ' )'
                : '()';

            $rV .= "\n" . $className . $functionName . $parameters;
        }

        $rV .= "\n";

        return $rV;
    }
1158030
private static function getDebugFile()
    {
        $trace = \debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);

        foreach (\array_reverse($trace) as $stackFrame) {
            if (!self::isDebugCall($stackFrame)) {
                continue;
            }

            if (\preg_match('/eval\(/', $stackFrame['file'])) {
                \preg_match_all('/([^\(]+)\((\d+)/', $stackFrame['file'], $matches);

                return $matches[1][0];
            }

            return $stackFrame['file'];
        }
    }
289251
public static function debugTrail() {
		$trail = debug_backtrace();
		$trail = array_reverse($trail);
		array_pop($trail);

		$path = array();
		foreach ($trail as $dat) {
			$pathFragment = $dat['class'] . $dat['type'] . $dat['function'];
				// add the path of the included file
			if (in_array($dat['function'], array('require', 'include', 'require_once', 'include_once'))) {
				$pathFragment .= '(' . substr($dat['args'][0], strlen(PATH_site)) . '),' . substr($dat['file'], strlen(PATH_site));
			}
			$path[] = $pathFragment . '#' . $dat['line'];
		}

		return implode(' // ', $path);
	}
1238850
public function analyze(
        Context $file_context = null,
        $preserve_analyzers = false,
        Context $global_context = null
    ) {
        $codebase = $this->project_analyzer->getCodebase();

        $file_storage = $codebase->file_storage_provider->get($this->file_path);

        if (!$file_storage->deep_scan && !$codebase->server_mode) {
            throw new UnpreparedAnalysisException('File ' . $this->file_path . ' has not been properly scanned');
        }

        if ($file_storage->has_visitor_issues) {
            return;
        }

        if ($file_context) {
            $this->context = $file_context;
        }

        if (!$this->context) {
            $this->context = new Context();
            $this->context->collect_references = $codebase->collect_references;
        }

        if ($codebase->config->useStrictTypesForFile($this->file_path)) {
            $this->context->strict_types = true;
        }

        $this->context->is_global = true;
        $this->context->defineGlobals();
        $this->context->collect_exceptions = $codebase->config->check_for_throws_in_global_scope;

        try {
            $stmts = $codebase->getStatementsForFile($this->file_path);
        } catch (PhpParser\Error $e) {
            return;
        }

        $statements_analyzer = new StatementsAnalyzer($this);

        $leftover_stmts = $this->populateCheckers($stmts);

        // if there are any leftover statements, evaluate them,
        // in turn causing the classes/interfaces be evaluated
        if ($leftover_stmts) {
            $statements_analyzer->analyze($leftover_stmts, $this->context, $global_context, true);
        }

        // check any leftover interfaces not already evaluated
        foreach ($this->interface_analyzers_to_analyze as $interface_analyzer) {
            $interface_analyzer->analyze();
        }

        // check any leftover classes not already evaluated

        foreach ($this->class_analyzers_to_analyze as $class_analyzer) {
            $class_analyzer->analyze(null, $this->context);
        }

        if (!$preserve_analyzers) {
            $this->class_analyzers_to_analyze = [];
            $this->interface_analyzers_to_analyze = [];
        }

        if ($codebase->config->check_for_throws_in_global_scope) {
            $uncaught_throws = $statements_analyzer->getUncaughtThrows($this->context);
            foreach ($uncaught_throws as $possibly_thrown_exception => $codelocations) {
                foreach ($codelocations as $codelocation) {
                    // issues are suppressed in ThrowAnalyzer, CallAnalyzer, etc.
                    if (IssueBuffer::accepts(
                        new UncaughtThrowInGlobalScope(
                            $possibly_thrown_exception . ' is thrown but not caught in global scope',
                            $codelocation
                        )
                    )) {
                        // fall through
                    }
                }
            }
        }
    }
765549
def trace_line_numbers(filename, reload_on_change=False):
    """"""
    fullname = cache_file(filename, reload_on_change)
    if not fullname: return None
    e = file_cache[filename]
    if not e.line_numbers:
        if hasattr(coverage.coverage, 'analyze_morf'):
            e.line_numbers = coverage.the_coverage.analyze_morf(fullname)[1]
        else:
            cov = coverage.coverage()
            cov._warn_no_data = False
            e.line_numbers = cov.analysis(fullname)[1]
            pass
        pass
    return e.line_numbers
259284
public static function dump()
	{
		if (\Fuel::$is_cli)
		{
			// no fancy flying, jump dump 'm
			foreach (func_get_args() as $arg)
			{
				var_dump($arg);
			}
		}
		else
		{
			$backtrace = debug_backtrace();

			// locate the first file entry that isn't this class itself
			foreach ($backtrace as $stack => $trace)
			{
				if (isset($trace['file']))
				{
					// If being called from within, show the file above in the backtrack
					if (strpos($trace['file'], 'core/classes/debug.php') !== false)
					{
						$callee = $backtrace[$stack+1];
						$label = \Inflector::humanize($backtrace[$stack+1]['function']);
					}
					else
					{
						$callee = $trace;
						$label = 'Debug';
					}

					$callee['file'] = \Fuel::clean_path($callee['file']);

					break;
				}
			}

			$arguments = func_get_args();

			if ( ! static::$js_displayed)
			{
				echo <<<JS
	<script type="text/javascript">function fuel_debug_toggle(a){if(document.getElementById){if(document.getElementById(a).style.display=="none"){document.getElementById(a).style.display="block"}else{document.getElementById(a).style.display="none"}}else{if(document.layers){if(document.id.display=="none"){document.id.display="block"}else{document.id.display="none"}}else{if(document.all.id.style.display=="none"){document.all.id.style.display="block"}else{document.all.id.style.display="none"}}}};</script>
JS;
				static::$js_displayed = true;
			}
			echo '<div class="fuelphp-dump" style="font-size: 13px;background: #EEE !important; border:1px solid #666; color: #000 !important; padding:10px;">';
			echo '<h1 style="border-bottom: 1px solid #CCC; padding: 0 0 5px 0; margin: 0 0 5px 0; font: bold 120% sans-serif;">'.$callee['file'].' @ line: '.$callee['line'].'</h1>';
			echo '<pre style="overflow:auto;font-size:100%;">';

			$count = count($arguments);
			for ($i = 1; $i <= $count; $i++)
			{
				echo '<strong>Variable #'.$i.':</strong>'.PHP_EOL;
				echo static::format('', $arguments[$i - 1]);
				echo PHP_EOL.PHP_EOL;
			}

			echo "</pre>";
			echo "</div>";
		}
	}
817371
static function getTrace($e, $seen = null)
    {
        $starter = $seen ? 'Caused by: ' : '';
        $result = array();
        if (!$seen) $seen = array();
        $trace  = $e->getTrace();
        $prev   = $e->getPrevious();
        $result[] = sprintf('%s%s: %s', $starter, get_class($e), $e->getMessage());
        $file = $e->getFile();
        $line = $e->getLine();

        while (true) {
            $current = "$file:$line";
            $result[] = sprintf(' at %s%s%s(%s%s%s)',
                    count($trace) && array_key_exists('class', $trace[0]) ? str_replace('\\', '.', $trace[0]['class']) : '',
                    count($trace) && array_key_exists('class', $trace[0]) && array_key_exists('function', $trace[0]) ? '.' : '',
                    count($trace) && array_key_exists('function', $trace[0]) ? str_replace('\\', '.', $trace[0]['function']) : '(main)',
                    $line === null ? $file : basename($file),
                    $line === null ? '' : ':',
                    $line === null ? '' : $line);
            if (is_array($seen))
                $seen[] = "$file:$line";
            if (!count($trace))
                break;
            $file = array_key_exists('file', $trace[0]) ? $trace[0]['file'] : 'Unknown Source';
            $line = array_key_exists('file', $trace[0]) && array_key_exists('line', $trace[0]) && $trace[0]['line'] ? $trace[0]['line'] : null;
            array_shift($trace);
        }

        $result = join("\n", $result);
        if ($prev)
            $result  .= "\n" . self::getTrace($prev, $seen);
        return $result;
    }
361429
protected static function get_calling_module_from_trace($backtrace)
    {
        if (!isset($backtrace[1]['file'])) {
            return null;
        }

        $callingfile = realpath($backtrace[1]['file']);

        return ModuleLoader::inst()->getManifest()->getModuleByPath($callingfile);
    }
1083510
private static function buildTraceStep( $trace, $i, $j, $breakMode = 0 )
	{
		if( $j == 0 )
			if( isset( $trace['function'] ) )
				if( in_array( $trace['function'], array( "eval", "throwException" ) ) )		//  Exception was thrown using throwException
					return "";

		$indent		= " ";
		$break		= "";
		if( $breakMode == 2 )
		{
			$indent		= str_repeat( "&nbsp;", 2 + strlen( $j ) );
			$break		= "<br/>".$indent;
		}
		if( $breakMode == 3 )
		{
			$break		= "";#_2_<br/>";
		}
		$funcBreak	= $break;
		if( $breakMode == 1 )
			$funcBreak	= "<br/>";

		$content	= "#$j ";
		if( isset( $trace["file"] ) )
			$content	.= self::trimRootPath( $trace["file"] )."(".$trace["line"]."): ".$funcBreak;
		if( array_key_exists( "class", $trace ) && array_key_exists( "type", $trace ) )
			$content	.= $indent.$trace["class"].$trace["type"];
		if( array_key_exists( "function", $trace ) )
		{
			$content	.= $trace["function"]."(";
			if( array_key_exists( "args", $trace ) )
			{
				if( count( $trace['args'] ) )
				{
					$argList	= array();
					foreach( $trace["args"] as $argument )
					{
						$type	= ucFirst( gettype( $argument ) );
						$string	= self::convertArgumentToString( $argument, $breakMode );
						$argList[]	= $type.": ".$string;
					}
					$argBreak	= $breakMode ? $break.$indent.$indent : " ";
					$arguments	= implode( ",".$argBreak, $argList );
					if( $breakMode == 3 )
					{
						$arguments	= self::blockquote( implode( ",<br/>", $argList ) );
					}
					$content	.= $argBreak.$arguments.$break;
				}
			}
			$content	.= ")<br/>";
		}
		return $content;
	}
886773
static public function traceMemory($context=null)
    {
        $caller = static::getCaller();
        $memory_usage = memory_get_usage();
        $message = sprintf('%30s::%-15s: %s', $caller['class'], $caller['function'], $memory_usage);
        if ($context) {
            $message .= ' ' . print_r($context, true);
        }
        
        Ioc::logger('trace')->debug(sprintf('[%s]%s', 'memory', $message));
    }
1241252
public function __trace()
    {
        $info['_attributes'] = $this->_attributes;
        $info['_changes'] = $this->_changes;
        $info['_checked'] = $this->_checked;
//        $info['_proto'] = $this->_proto;
//        $info['_parent'] = $this->_parent;
        $info['_children'] = $this->_children;

//        if ($this->_errors) $info['_errors'] = $this->_errors->toArrayCompact(false);
        return $info;
    }
898724
private function renderTrace($trace)
    {
        foreach ($trace as $i => $entry) {
            $s = '';
            if (!empty($entry['file'])) {
                $s .= $this->stripFile($entry['file']);
                if (!empty($entry['line'])) {
                    $s .= ' (line ' . $entry['line'] . ')';
                }
            }
            if (!empty($entry['function'])) {
                $class = !empty($entry['class']) ? $entry['class'] . $entry['type'] : '';
                $args  = !empty($entry['args']) ? $this->dumpArgs($entry['args']) : '' ;
                $s .= ':<br/>&nbsp;&nbsp;&nbsp;' . $class . $entry['function'] . '(' . $args . ')';
            }
            $trace[$i] = '<li>' . $s . '</li>';
        }

        return '<code><ul>' . implode('<br/>', $trace) . '</ul></code>';
    }