Coder Social home page Coder Social logo

hhvm / xhp-lib Goto Github PK

View Code? Open in Web Editor NEW
1.4K 86.0 162.0 1.79 MB

Class libraries for XHP. XHP is a Hack feature that augments the syntax of the language such that XML document fragments become valid Hack expressions.

Home Page: http://facebook.github.io/xhp-lib/

License: MIT License

Hack 100.00%
facebook hacklang hack xhp

xhp-lib's Introduction

XHP Logo

Build Status

Introduction

XHP augments the syntax of Hack such that XML document fragments become valid Hack expressions. This allows you to use Hack as a stricter templating engine and offers much more straightforward implementation of reusable components.

For a practical example of high level components you can build with xhp, you might want to take a look at the archived project xhp-bootstrap.

Announcements and articles are posted to The HHVM blog and were previously posted to the XHP-Lib blog

Installation

Composer is the recommended installation method. To add XHP to your project, run the following command :

$ composer require facebook/xhp-lib

Simple Example

$href = 'http://www.facebook.com';
$link = <a href={$href}>Facebook</a>;

Take note of the syntax on line 2 ($link = ...), this is not a string. This is the major new syntax that XHP introduces to Hack. The <a ...> syntax is used to instantiate an object of the a class.

Notice the assignment to href={$href}. This is not string interpolation. It is setting the attribute $link->:href. Anything that's in {}'s is interpreted as a full Hack expression. This differs from {}'s in double-quoted strings; double-quoted strings can only contain variables.

You can define arbitrary elements that can be instantiated in Hack. Under the covers each element you create is an instance of a class. To define new elements you just define a new class. XHP comes with a set of predefined elements which implement most of HTML for you.

Complex Structures

Note that XHP structures can be arbitrarily complex. This is a valid XHP program:

$post =
  <div class="post">
    <h2>{$post}</h2>
    <p><span>Hey there.</span></p>
    <a href={$like_link}>Like</a>
  </div>;

One advantage that XHP has over string construction is that it enforces correct markup structure at compile time. That is, the expression $foo = <h1>Header</h2>; is not a valid expression, because you can not close an h1 tag with a /h2. When building large chunks of markup it can be difficult to be totally correct. With XHP the compiler now checks your work and will refuse to run until the markup is correct.

Dynamic Structures

Sometimes it may be useful to create a bunch of elements and dynamically add them as children to an element. All XHP objects support the appendChild method which behaves similarly to the same Javascript method. For example:

$list = <ul />;
$items = ...;

foreach ($items as $item) {
  $list->appendChild(<li>{$item}</li>);
}

In the code, <ul /> creates a ul with no children. Then we dynamically append children to it for each item in the $items list.

Alternatively, you can pass an array of children to <ul>...</ul> instead. This is especially useful when dealing with larger xhp trees where it would be harder to get a variable reference to the ul.

$list_items = vec[];
$items = ...;

foreach($items as $item) {
  $list_items[] = <li>{$item}</li>;
}

$list = <div><ul>{$list_items}</ul></div>;

Escaping

An interesting feature of XHP is the idea of automatic escaping. If you want to render input from the user without using XHP, you must manually escape it. This practice is error-prone and has been proven over time to be an untenable solution. It increases code complexity and still leads to security vulnerabilities by careless programming. However, since XHP has context-specific about the page structure it can automatically escape data. The following two examples are identical, and both are "safe".

$hello = '<div>Hello '.htmlspecialchars($name).'</div>';
$hello = <div>Hello {$name}</div>;

As you can see, using XHP makes safety the default rather than the exception.

Defining Elements

All elements in XHP are just Hack classes. Even the basic HTML elements like div and span are classes. You define an element using the xhp class modifier to specify that you're creating an XHP element:

use namespace Facebook\XHP\Core as x;

xhp class thing extends x\element {
  ...
}

Notice that we are extending x\element. The name x\element is a common shorthand for Facebook\XHP\Core\element. The use statement use namespace Facebook\XHP\Core as x; is commonly used in files that use xhp-lib. The use clause will be left out in future examples as x\... has become the canonical name for Core for historical reasons.

After we define thing we can instantiate it with the expression <thing />. x\element is the core XHP class you should subclass from when defining an element. It will provide you all the methods you need like appendChild, and so on. As an x\element you must define only renderAsync(). renderAsync() should always return more XHP elements. It's important to remember this rule: even elements you define yourself will return XHP elements. The only XHP elements that are allowed to return a string are elements which subclass from x\primitive. The only elements which should subclass x\primitive are base elements that make HTML building blocks. XHP with the core HTML library is a viable replacement for strings of markup.

Defining Attributes

Most elements will take some number of attributes which affect its behavior. You define attributes in an element with the attribute keyword.

xhp class thing extends x\element {
  attribute
    string title = "No Title",
    string sub-title,
    float fill-percentage @required;
}

Here we define three attributes, title, sub-title, and fill-percentage. title is of type string and the default value is "No Title". sub-title is of type ?string. The attribute is optional and does not have a default value. Hack will therefore infer that sub-title will be null when you do not set it. fill-percentage is of type float and it is required. Because it is required, xhp-lib will throw during render or when accessing $thing->:fill-percentage if no value has been set. Hack can therefore be certain that the value will not be null.

Note that when you extend another element you will always inherit its attributes. However, any attributes you specify with the same name will override your parent's attributes.

You can also copy another element's attribute declarations by specifying only a tag name in a definition. The declaration attribute :div says that this element may accept any attribute that a div element could accept.

Defining Element Structure

All elements have some kind of structure that they must follow. For instance, in HTML5 it is illegal for an <input /> to appear directly inside of a <body /> tag (it must be inside a form). XHP allows you to define a content model which documents must adhere to. This is done with the XHPChild\Validation trait. XHPChild\Validation is short for Facebook\XHP\ChildValidation\Validation. The use clause use namespace Facebook\XHP\ChildValidation as XHPChild is often use in files declaring xhp classes. The use clause will be left out in the examples.

xhp class thing_container extends x\element {
  abstract protected static function getChildrenDeclaration(): XHPChild\Constraint {
    return XHPChild\any_number_of(
      XHPChild\any_of(
        XHPChild\of_type<thing>(),
        XHPChild\pcdata(),
      )
    );
  }
}

For the full list of constraints you can formulate, see the list of ChildValidation functions. The example above composes the following rules. The top-level rule any_number_of() declares that there may be zero or more children, which all match the inner constraint. The inner constraint says that a child is valid when matches any_of the following constraints: It is an object of type thing or flat text (pcdata).

Element Categories

A lot of times you may want to accept all children of a particular group, but enumerating the group starts to become unsustainable. When this happens you can use an interface as a marker to denote membership of a group. A good example is how all the built-in html elements implement the Category interfaces which match to the html-spec categories.

Here is an example of the category Flow being used in the <audio> element children definition.:

  protected static function getChildrenDeclaration(): XHPChild\Constraint {
    return XHPChild\sequence(
      XHPChild\any_number_of(XHPChild\of_type<source>()),
      XHPChild\any_number_of(XHPChild\of_type<track>()),
      XHPChild\any_number_of(
        XHPChild\any_of(XHPChild\pcdata(), XHPChild\of_type<Category\Flow>()),
      ),
    );
  }

Asynchronous data fetching

XHP supports Hack's 'async' functionality, allowing you to build components that efficiently fetch the data that they require:

xhp class async_thing extends :x:element {
  protected async function renderAsync(): Awaitable<x\node> {
    $db = await AsyncMysqlClient::connect(...);
    $result = await $db->queryf(
      'SELECT id2 FROM %T WHERE id1 %=d',
      'friends',
      $this->getContext('viewer')->getUserID(),
    );

    $rows = $result->dictRowsTyped();
    $friend_ids = Vec\map($rows, $row ==> $row['id2']);
    $friend_data = await Vec\map_async(
      $friend_ids,
      $id ==> User::get($id),
    );

    $out = <ul />;
    foreach ($friend_ids as $id) {
      $out->appendChild(<li>.... </li>);
    }

    return $out;
  }
}

When an XHP tree is rendered, renderAsync() is called for all children, and data fetching happens in parallel. This allows the data dependencies of your components to efficiently be an implementation detail instead of having it as part of the API and passed by the user (eg in an attribute).

Whitespace

In XHP, text nodes that contain only whitespace are removed. The expressions <div> </div> and <div /> are identical. Text nodes that contain non-whitespace are trimmed on the left and right to at most 1 space. This is worth noting because you may want to do something like:

$node = <div><label>Title:</label> <span>{$title}</span></div>;

This will lead to non-desirable results as the space between the : and $title will be lost. In order to fix this try moving the space into the <label /> tag. If you can't do this then just use {' '} which will not be stripped.

Best Practices

There are certain conventions that you should comply with while using XHP.

  • Don't pollute the global XHP namespace with namespace-less elements. Most elements you define should use some namespace. Elements that use no namespace should not be "magic" at all. For instance,
xhp class fb:thing extends x\element {
  protected async function renderAsync(): Awaitable<x\node> {
    return <div class="thing">thing</div>;
  }
}

This element would be considered magic because when you print an <fb:thing /> it actually returns a div.

External Resources

Below are a list of external resources about XHP:

  • Code Before the Horse - Basic XHP introduction, examples, and lessons learned from Facebook written by one of their UI Engineers.

License

This software is MIT-licensed.

xhp-lib's People

Contributors

aloiret avatar amritpalsingh5191 avatar atry avatar ayurmedia avatar azjezz avatar daniel15 avatar fredemmott avatar haiping avatar jjergus avatar jvaelen avatar jwatzman avatar karoun avatar kmeht avatar lexidor avatar metagoto avatar ngavalas avatar rob0rt avatar scottmac avatar sdknjg8zxq avatar simonwelsh avatar ssandler avatar steelbrain avatar steveluscher avatar swahvay avatar tj09 avatar waldyrious avatar wilfred avatar wlin53 avatar xxtanisxx avatar yungsters avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

xhp-lib's Issues

Mac/Apache: Seg fault

I just started first simple tests for XHP. I installed the extension on my local Apache (Mac OS X 10.6.6, enabling "Web sharing"). The strange thing is: Depending on the interpreted XHP-source the page will not load ("Website is not avaible"/"Empty response") - but not every time. Without changing the source, the behaviour changes. There's almost no code which gets executed every time - but the probability that loading fails, differs.
The apache-logs show segmentation faults.

[Sun Jan 16 16:44:37 2011] [notice] child pid 16452 exit signal Segmentation fault (11)

__toString() should not throw Exceptions

__toString() should not throw Exceptions. This is correct for :x:primitive, but not for :x:element which will throw a fatal error without providing any information about the original error. This makes debugging a PITA so the behaviour from :x:primitive should be applied to :x:element too.

Invalid result for anonymous function

Input code

<?php

$this['something'] = $that->attr->call("arg", $something);
$a = function() { return 10; };

invoke()['xhp'];

Result code (using xhpize)

<?php

$this['something']=$that->attr->call("arg",$something);
$a=function()->call("arg",$something){return 10;};

__xhp_idx(invoke(), 'xhp');

Make fails in centos 5

Versions:
bison 2.3
flex 2.5.4
re2c 0.13.5
gcc 4.1.2
php 5.3.3

configure is successful, but make yields:

/usr/bin/flex: unknown flag '-'.  For usage, try
/usr/bin/flex --help
make[1]: *** [scanner.lex.cpp] Error 1
make[1]: Leaving directory `/home/admin/xhp/xhp'
make: *** [xhp/libxhp.a] Error 2

Install failing... static library xhp/libxhp.a is not portable, etc

Would really love to start implementing this great extension in our facebook app development.

Warnings during configure:

scanner.lex.cpp:9670: warning: unused variable ‘yyg’

Warnings during make:

*** Warning: Linking the shared library xhp.la against the
*** static library xhp/libxhp.a is not portable!

Fails all 19 tests of make test

When xhp.so is included in php.ini, get a server misconfiguration error.

Pastebin w/ output:

http://pastebin.com/s3jZmRNm

Installed from the 1.3.7 tagged release

Red Hat Enterprise Linux Server release 5.4 (Tikanga)
gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-46)
PHP 5.3.1 (cli) (built: Feb 24 2010 00:00:26)
re2c 0.13.5

Thanks,

Chado

Fatal error: Class 'xhp_a' not found

I just installed this on a fresh Linode with a basic Ubuntu 9.10 LAMP stack with all the latest dependencies. It built ok, and the module shows up in phpinfo(), but when I try to run any of the example code, I get an error:

Fatal error: Class 'xhp_a' not found in /home/me/public_html/test.php  on line 3

Here's the code I tested with:

Facebook;

I tried running the code through the xhpize tool, and got the following output:

 $href,), array('Facebook',), __FILE__, 3);

Which produces the same "class not found" error.

XHP fails with `or`, `xor`, `and` operators

marcel@dev050 ~/xhp/xhp $ cat a.php
<?php
$x = 1 XOR 2;
<a />;
marcel@dev050 ~/xhp/xhp $ cat a.php | ./xhpize 
<?php
$x=1XOR2;
new xhp_a(array(), array(), __FILE__, 3);File `-` xhpized.

:x:primitive vs :x:element

I haven't quite figured out the difference between :x:primitive and :x:element, apart from one uses the method stringify() and one uses render(). After watching "XHP: Object Oriented XML in PHP Tech Talk" it seems that :x:primitive should be used when returning raw HTML (E.g. :x:doctype) and :x:element should be used when returning XHP elements (E.g. <ui:form:input>).

Is this logic correct? The comments in the file aren't very clear. Hopefully it will help others getting used to XHP too.

Invalid markup with disabled attribute

In html.php you'll see many declarations of attribute bool disabled which, if set, will be rendered as <tag disabled="1">foo</tag>. It should be rendered either as disabled="disabled" (XHTML compliant) or as disabled to render the correct markup but I don't believe XHP supports attribute minimization at this time.

Element Instantiation Question (am I misunderstanding XHP?)

Slightly confused about the syntax for element instantiation.. am I misunderstanding XHP?

Would love to start writing new namespace elements to use as front-end components for quick reuse...

...is this an appropriate use of XHP?

Actual attempt, seems if I echo the element it works, if I embed the element in a broader chunk of html it fails...

ie: http://pastebin.com/JWGseQfN

... do we have any basic examples of the proper way to define and instantiate elements in the broader scope of a front end template? Any source examples of the "right way" to use XHP would be very helpful.

... also, is there a discussion forum anywhere for XHP? Do not want to pollute the github ticketing system.

Thanks everyone,

Chado

XHP unit tests

What is the testing framework in use? Is it something standalone? Thanks.

Parser bug

$ cat test.php

; function f() {} $ php -l test.php [23186:0000001:0001] [fb1.8.2] Fatal PHP Parse error: syntax error, unexpected T_STRING in test.php on line 4 PHP Parse error: syntax error, unexpected T_STRING in test.php on line 4 Errors parsing test.php

Build for Windows

I know it will be an unpopular request to make, and if I could move all my developers off of Windows to Linux I wouldn't have to make it - but is there any chance of getting a config.w32 file created to work towards Windows support? I'll happily create the .dll file, but I don't even know where to being in making the app M$-friendly. (Given that all of the requirements run on Windows, I'd hope that getting this extension built won't be as touch as something like php_memcached.dll)

Fatal error: Class 'xhp_form' not found on line 7

Installed the extension and tried to run the example:

Hello, {$_POST['name']};
} else {
  echo
    
      What is your name?
; }
# php -v
PHP 5.2.11 (cli) (built: Oct 19 2009 14:35:59) 
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2009 Zend Technologies
    with XCache v1.2.2, Copyright (c) 2005-2007, by mOo

CPPFLAGS not passed to xhp/Makefile

Passing CPPFLAGS to ./configure correctly sets them in Makefile, though not in xhp/Makefile, so compiling with custom C++ include paths requires manually editing that file.

Segmentation fault (11)

I just installed XHP for the first time. When I add require_once 'xhp/init.php'; and reload the page I get child pid XXXX exit signal Segmentation fault (11). This is a gist of my phpinfo page: https://gist.github.com/b3eefb174d105de3077b (too bad you can't render it in Gist, oh well).

Any help is appreciated. I'd love help smooth the install process and write some tutorials once I get up and running. Thanks!

I'm on a MBP running 10.6 with stock Apache and PHP.

Unused variable in xhp/scanner.lex.cpp

When compiling xhp I get the following error :
/home/../xhp/xhp/scanner.lex.cpp: In function ‘yy_state_type yy_try_NUL_trans(yy_state_type, void*)’:
/home/../xhp/xhp/scanner.lex.cpp:9411: warning: unused variable ‘yyg’

I think this can be easily fixed, and the annoying warning from GCC will be fixed :)
(tested with GCC 4.4.1)

compile error on osx Lion

I am having trouble compiling on osx Lion. The version of gcc is 4.2.1. The error looks like the rope interface has changed:

76-14-49-209:xhp chris$ make
make  -C /Users/chris/dev/xhp/xhp libxhp.a
g++ -c -fPIC -g -Wall -O3 -minline-all-stringops -o code_rope.o code_rope.cpp
/usr/include/c++/4.2.1/ext/ropeimpl.h: In static member function ‘static typename __gnu_cxx::rope<_CharT, _Alloc>::_RopeRep* __gnu_cxx::rope<_CharT, _Alloc>::_S_substring(__gnu_cxx::_Rope_RopeRep<_CharT, _Alloc>*, size_t, size_t) [with _CharT = char, _Alloc = __gnu_cxx::__pool_alloc<char>]’:
/usr/include/c++/4.2.1/ext/rope:1868:   instantiated from ‘void __gnu_cxx::rope<_CharT, _Alloc>::pop_back() [with _CharT = char, _Alloc = __gnu_cxx::__pool_alloc<char>]’
code_rope.cpp:58:   instantiated from here
/usr/include/c++/4.2.1/ext/ropeimpl.h:819: error: ‘_Data_allocate’ is not a member of ‘__gnu_cxx::__pool_alloc<char>’
/usr/include/c++/4.2.1/ext/ropeimpl.h: In static member function ‘static typename __gnu_cxx::rope<_CharT, _Alloc>::_RopeLeaf* __gnu_cxx::rope<_CharT, _Alloc>::_S_leaf_concat_char_iter(__gnu_cxx::_Rope_RopeLeaf<_CharT, _Alloc>*, const _CharT*, size_t) [with _CharT = char, _Alloc = __gnu_cxx::__pool_alloc<char>]’:
/usr/include/c++/4.2.1/ext/ropeimpl.h:675:   instantiated from ‘static typename __gnu_cxx::rope<_CharT, _Alloc>::_RopeRep* __gnu_cxx::rope<_CharT, _Alloc>::_S_concat(__gnu_cxx::_Rope_RopeRep<_CharT, _Alloc>*, __gnu_cxx::_Rope_RopeRep<_CharT, _Alloc>*) [with _CharT = char, _Alloc = __gnu_cxx::__pool_alloc<char>]’
/usr/include/c++/4.2.1/ext/rope:2763:   instantiated from ‘__gnu_cxx::rope<_CharT, _Alloc> __gnu_cxx::operator+(const __gnu_cxx::rope<_CharT, _Alloc>&, const __gnu_cxx::rope<_CharT, _Alloc>&) [with _CharT = char, _Alloc = __gnu_cxx::__pool_alloc<char>]’
code_rope.cpp:50:   instantiated from here
/usr/include/c++/4.2.1/ext/ropeimpl.h:436: error: ‘_Data_allocate’ is not a member of ‘__gnu_cxx::__pool_alloc<char>’
make[1]: *** [code_rope.o] Error 1
make: *** [/Users/chris/dev/xhp/xhp/libxhp.a] Error 2

<style> fails with colons

Example:

echo <style>
.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}
</style>;

PHP Parse error:  syntax error, unexpected ':' in index.php on line 38

Another thing I noticed is XHP doesn't like empty CSS rules. Although practically pointless, the W3C validator reports it's quasi-valid. It doesn't affect me personally so I won't push for change. :)

echo <style>
.clearfix:after {
}
</style>;

PHP Parse error:  syntax error, unexpected '}' in index.php on line 38

Make getChildren(), getFirstChild() and getLastChild() public

In current implementation,

:xhp::getChildren($selector = null);
:xhp::getFirstChild($selector = null);
:xhp::getLastChild($selector = null);

are protected. I changed them to public in my current local copy to implement a custom getElementById function. And it works.

public function getElementById(:xhp $elem, string $id): ?:xhp
{
    $children = $elem->getChildren();

    foreach ($children as $child)
    {
        if ($child instanceof :xhp)
        {
            if ($child->isAttributeSet("id") && $child->getAttribute("id") === $id)
            {
                return $child;
            }

            $res = $this->getElementById($child, $id);

            if ($res !== null)
            {
                return $res;
            }
        }
    }

    return null;
}

Example call:

$x = $this->getElementById($this->my_xhp_code, "menu-header");
$x->prependChild(<br/>);

Why do you limit the access to children? Is there a specific reason? I can't see a valid reason to do that. Please change this or give an explanation please :-)

Can't make test under ubuntu 13.04 with g++ 4.7.3

I cloned the git compiled it with phpize5, configured. To this point everything seems ok. Then I tried to "make" and I got these errors:

make  -C /home/sinan/xhp/xhp/xhp libxhp.a
make[1]: Enter directory '/home/sinan/xhp/xhp/xhp'
g++ -c -fPIC -g -Wall -O3 -minline-all-stringops -o code_rope.o code_rope.cpp
`which flex35 2>/dev/null || which flex 2>/dev/null` \
      -C --header-file=scanner.lex.hpp -o scanner.lex.cpp -d scanner.l
/bin/sh: 1: -C: not found
make[1]: *** [scanner.lex.cpp] Error 127
make[1]: Exit directory '/home/sinan/xhp/xhp/xhp'
make: *** [/home/sinan/xhp/xhp/xhp/libxhp.a] Error 2

XHP doesn't work with some HEREDOC expressions

Given a source file like:

<?php
$foo = <<<EOF
?>
EOF;
$bar = <a />;`

You will get a parse error. The XHP-detection fastpath in fastpath.re is not aware of HEREDOC syntax and will therefore consider everything inside a HEREDOC as if it were PHP. If you have something that changes state like a quote or closing PHP tag it will alter the fastpath's understanding of the program.

XHP Error: /** comment before attribute of user-defined type

from Mihai:

Hi,

I think I've found a bug in XHP. If you can't reproduce it from this
description, I'll link to my diff (it will be ready later today).

I'm using this code:

class :my:element extends :x:element {
attribute
// ... other attributes
/**
* comment
*/
MyClass request @required,
// ... other attributes and code

}

I'm calling this class from another file:
return <my:element request={new MyClass}
// ...
/>;

When I open the relevant page (that calls all this code) in my browser I
get:

Error: XHPInvalidAttributeException
Invalid attribute `request` of type `MyClass`
supplied to element `:my:element`, expected `/**
* commet
*/
MyClass`.

I've attached the whole error page.

This ONLY happens if the comment above the attribute starts with /** AND
the attribute type is a user-defined class.
If the comment starts with /* there's no problem.
If the type is var' orstring' there's no problem.

Is this a parsing problem? Is it known?

Don't throw exceptions in __toString

:xhp:raw-pcdata-element::stringify() can throw an exception, which is not allowed by PHP as it can occur in a __toString call (renderChild method). This is enforced by PHP 5.5 which will throw a fatal error if you try to throw an exception in a __toString call (effectively getting rid of all the exception information 👎)

XHP fails with PHP 5.4

PHP Fatal error:  Declaration of xhp_x__composable_element::__construct() must be compatible with xhp_x__base::__construct() in /home/nathan/xhp/php-lib/core.php on line 534

I never had this issue with PHP 5.3, but even though this project seems unmaintained (BOOO!) someone might find the time to fix it up.

xhp/scanner.lex.o included in source

This file appears to be compiled as x86_64, and so if targeted builds for other architectures fail.

Resolved by deleting file and allowing it to be recompiled

unexpected ':'

Hi,

I'm getting the error:

the xhp test command worked fine!

"PHP Parse error: syntax error, unexpected ':', expecting T_STRING in xhp/php-lib/core.php

Compiling for Zend Server CE on Mac OS

Hi, I had a little bit of trouble while compiling this great extension on my "Snow Leopard" machine with Zend Server. What I've found out is that ZS PHP5.3 is 32bit and I was building a 64bit library.

Then I tried running ./configure like this (found some tips on Apple Developers Forum):

./configure --with-php-config=/usr/local/zend/bin/php-config --target=i386-apple-darwin10.4.0 --build=i386-apple-darwin10.4.0 --host=i386-apple-darwin10.4.0 CFLAGS='-arch i386' LDFLAGS='-arch i386'  CC='gcc -m32' CXX='g++ -m32' CHOST='i386-apple-darwin10.4.0' CPPFLAGS='-arch i386'

This compiled the extension, but php could not load it because of external symbol 'xhp_preprocess' was not found, though the 'file xhp.so' showed extension to be 32bit.

After a little bit of investigation I found a problem and a solution (I'm not a unix Makefile guru so this might sound like an awful hack, sorry). Here it is:

almost at the top of xhp/Makefile (where it's building libxhp.so) I've changed this line:

g++ -shared -Wl,-soname,libxhp.so -o libxhp.so $^

with this one:

g++ -m32 -shared -Wl,-arch,i386 -o libxhp.so $^

because, I don't know why, the LDFLAGS='-arch i386' used in ./configure doesn't come up to that part, so I'm adding the parameter manually. Also the '-soname' option is not supported on "Snow Leopard" g++ compiler (LD was complaining about unknown parameters).

This small fix did the magic and I was able to play with XHP on MacOS 10.6 with ZS.

The problem was that everything was compiled in 32bits, but the linker tried to make libxhp.so as a x86_64 library.

PHP 5.3.1 build undefined symbol zend_stream_getc

After building the extension and loading it in PHP I get:

PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib/php/modules/xhp.so' - /usr/lib/php/modules/xhp.so: undefined symbol: _Z16zend_stream_getcP17_zend_file_handle in Unknown on line 0

Being a novice at c, I'm not sure how to fix this. zend_file_handle is in zend_stream.h, which if I include doesn't seem to fix it.

Quotes in attributes output invalid HTML

Quotes in attributes are not escaped.

$a = <a/>
$a->setAttribute('title', "\"foo\"");
print $a; // <a title=""foo"">

Here's how I fixed it:

xhp/php-lib/html.php:86
protected final function renderBaseAttrs() {
    $buf = '<'.$this->tagName;
    foreach ($this->getAttributes() as $key => $val) {
      if ($val !== null && $val !== false) {
        $buf .= ' ' . htmlspecialchars($key) . '="' . htmlspecialchars($val, true) . '"';
      }
    }
    return $buf;
  }

From the above piece of code, change this part:

htmlspecialchars($val, true)

into:

htmlspecialchars($val, ENT_QUOTES)

xhp does not prefix class names with the \ prefix and therefore cannot be used within a php namespace

PHP 5.3 requires class namespaces to be explicit, even for classes that are in the global namespace. The XHP-generated source code does not provide a \ prefix on class names so when used within a namespace declaration the generated code fails with a fatal error, e.g.:

Fatal error: Class 'my\current\namespace\xhp_div' not found in /path/to/file ...

I think the only workaround currently would be to manually import each of the xhp classes into the current namespace and unfortunately the backslash namespace prefix would cause generated code to be incompatible with php 5.2.

XHP preprocessor produces syntax errors

See this minimal working example:

<?php

$foo = $bar === null ? 0 : $bar['baz'];
foo(function() { return [ 'bar' => 10 ]; });
foo(function() { return bar()[0]; });

After xhpize:

<?php

$foo=$bar===null?0:$bar['baz'];
foo(function()[{return array('bar'=>10);});
foo(function()[{return bar()[0];});

Same issue when using the xhp.so extension.

Unable to use callable attributes

When type hinting an attribute, it's currently not possible to use the callable type. Attempting to do so looks like the attribute validation is checking if the value is an instance of a "callable" class.

Example:

<?php

class :ex:call extends :x:element {
attribute callable callback;
}

$elem = <ex:call />;
$elem->setAttribute('callback', function() {});

My current workaround is to use var as the type and then an is_callable() check before using the value.

Select Nodes

Is there a way to select a specific node of the whole object? I was thinking something along the lines of a CSS selector.

undefined symbol: _Z19zend_error_noreturniPKcz

After building the xhp extension (1.3.9), apache fails to startup with the following error:

PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib64/php/modules/xhp.so' - /usr/lib64/php/modules/xhp.so: undefined symbol: _Z19zend_error_noreturniPKcz in Unknown on line 0

Seems like this may be related to issue #4, but that was supposedly fixed in 1.3.8?

Here is my build output: http://pastebin.com/jpa79Q5v

Fedora 11
gcc-4.4.0-4.x86_64

35/35 tests fail

PHP : /usr/bin/php
PHP_SAPI : cli
PHP_VERSION : 5.2.6-1+lenny8
ZEND_VERSION: 2.2.0
PHP_OS : Linux - Linux bear 2.6.33.1 #1 SMP Tue Apr 13 11:08:03 IST 2010 i686
INI actual : /etc/php5/cli/php.ini
More .INIs : /etc/php5/cli/conf.d/curl.ini,/etc/php5/cli/conf.d/ffmpeg.ini,/etc/php5/cli/conf.d/gd.ini,/etc/php5/cli/conf.d/mcrypt.ini,/etc/php5/cli/conf.d/memcache.ini,/etc/php5/cli/conf.d/mt.ini,/etc/php5/cli/conf.d/mysql.ini,/etc/php5/cli/conf.d/mysqli.ini,/etc/php5/cli/conf.d/pdo.ini,/etc/php5/cli/conf.d/pdo_mysql.ini,/etc/php5/cli/conf.d/pdo_sqlite.ini,/etc/php5/cli/conf.d/sqlite.ini
CWD : /home/martin/tmp/facebook-xhp-c78f8f2
Extra dirs :

Number of tests : 35 35
Tests skipped : 0 ( 0.0%) --------
Tests warned : 0 ( 0.0%) ( 0.0%)
Tests failed : 35 (100.0%) (100.0%)

Tests passed : 0 ( 0.0%) ( 0.0%)

Time taken : 1 seconds

When I try an actual test it fails with:


Fatal error: Class 'xhp_span' not found in....

PHP 5.3 Anonymous Functions Not Yet Supported?

Hello,
So I'd like to make a note that although this works:
function foo(){
return array('foo','bar');
}
echo foo()[1]; // output bar

this also works: echo array('foo','bar')[1]; // output bar

This does not work yet:
echo (function foo(){ return array('foo','bar');})()[1];

Which could potentially be useful... or maybe not, in any case it is not yet supported.
Thanks!!! WOO XHP!

php-lib convert php to hh

Apparently when include init.php I get an error when I run hhvm filename

Error is unexpected ':' in core.php line 18

issue with function xhp_x__base::__xhpAttributeDeclaration()?

I did a fresh clone from github and got the below error
ErrorException [ Strict ]: Static function xhp_x__base::__xhpAttributeDeclaration() should not be abstract

I hacked it here to fix it: jshaw86@c5457f4, i didn't do a code trace though so I'm not sure what exactly the implication of the fix is. I'm running PHP 5.3.5 in strict error mode, I'll submit a pull request if that is actually correct.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.