Class: JsDuck::Js::Property

Inherits:
Object
  • Object
show all
Includes:
Util::Singleton
Defined in:
lib/jsduck/js/property.rb

Overview

Auto-detection of properties.

Instance Method Summary collapse

Methods included from Util::Singleton

included

Instance Method Details

#detect(ast) ⇒ Object

Checks if AST node is a property, and if so, returns doc-hash with property name and various auto-detected attributes. When not a property returns nil.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/jsduck/js/property.rb', line 13

def detect(ast)
  exp = ast.expression_statement? ? ast["expression"] : nil
  var = ast.variable_declaration? ? ast["declarations"][0] : nil

  # foo = ...
  if exp && exp.assignment_expression?
    make(exp["left"].to_s, exp["right"])

    # var foo = ...
  elsif var
    make(var["id"].to_s, var["init"])

    # foo: ...
  elsif ast.property?
    make(ast["key"].key_value, ast["value"])

    # foo;
  elsif exp && exp.identifier?
    make(exp.to_s)

    # "foo"  (inside some expression)
  elsif ast.string?
    make(ast.to_value)

    # "foo";  (as a statement of it's own)
  elsif exp && exp.string?
    make(exp.to_value)

    # Object.defineProperty(obj, "prop", {value: x})
  elsif exp && exp.define_property?
    name = exp["arguments"][1].to_value

    if exp.object_descriptor("set")
      # Object with a setter is not readonly
      make(name)
    elsif exp.object_descriptor("get")
      # Object with a getter and no setter is readonly
      make(name, nil, true)
    else
      writable = exp.object_descriptor("writable")
      readonly = writable ? !writable.to_value : true
      make(name, exp.object_descriptor("value"), readonly)
    end

  else
    nil
  end
end

#make(name = nil, ast = nil, readonly = nil) ⇒ Object

Produces a doc-hash for a property.



63
64
65
66
67
68
69
70
71
# File 'lib/jsduck/js/property.rb', line 63

def make(name=nil, ast=nil, readonly=nil)
  return {
    :tagname => :property,
    :name => name,
    :type => ast && ast.value_type,
    :default => ast && default(ast),
    :readonly => readonly,
  }
end